我对jQueryAjax很陌生,我现在只学会了如何发送Ajax请求。我的问题是如何准备一个文件,以便能够发送响应作为回报?比方说,我的Ajax请求的url是process.php,我如何准备process.php文件,以便接收数据类型html或文本的响应?我知道这个问题听起来很奇怪,但我更关心的是处理响应的方法,而不是发送请求。请帮帮我吧,多谢!
1条回答 默认 最新
weixin_33727510 2015-01-17 13:00关注Your PHP endpoint will receive the data using e.g. POST (you can use GET if you like).
Then you need to reply in HTML, JSON, or plain text.
In the example below, you send
$.POSTwith adatavalue of, say,{ cmd: 'time' }.// Read command. No command is equivalent to an empty string. $cmd = empty($_POST['cmd']) ? '' : $_POST['cmd']; // Do something with the command. switch($cmd) { case '': // Empty string $reply = "You asked nothing"; break; case 'time': $reply = date('Y-m-d H:i:s'); break; default: $reply = "You asked a unexpected question"; break; } /* Text */ Header('Content-Type: text/plain;charset=utf8'); die($reply); /* HTML */ Header('Content-Type: text/html;charset=utf8'); die($reply); // This should contain valid HTML /* JSON, used to send structured data */ $reply = array( 'status' => 'OK', 'message'=> 'All good', 'reply' => $reply, ); Header('Content-Type: application/json;charset=utf8'); die(json_encode($reply));In the last case, your callback function will receive an object with members status, message and reply:
success: function(data) { if (!data.status) { alert("Unexpected return from AJAX endpoint: " + data); return; } if ('OK' == data.status) { alert(data.reply); return; } alert("AJAX signaled error: " + data.message); }解决 无用评论 打赏 举报