当您以这种方式应答 POST 调用时,您需要 三个 东西 - 从 _POST 读取数据,将其正确放在那里,然后以 JSON 格式应答。
$.ajax({
type: "POST",
url: 'signage.php',
data: {
subDir: val,
}
success: function(answer)
{
alert("server said: " + answer.data);
}
});
也可以:
$.post(
'signage.php',
{
subDir: val
},
function(answer){
alert("server said: " + answer.data);
}
}
然后在响应中:
<?php
if (array_key_exists('subDir', $_POST)) {
$subDir = $_POST['subDir'];
$answer = array(
'data' => "You said, '{$subDir}'",
);
header("Content-Type: application/json;charset=utf-8");
print json_encode($answer);
exit();
}
请注意,在响应中,您必须设置 Content-Type 并且必须发送有效的 JSON,这通常意味着您必须在发送 JSON 数据包后立即退出,以确保不发送任何其他内容。此外,响应必须尽快到达,并且之前不得包含任何其他内容(甚至在
还要注意,使用isset 是有风险的,因为您不能发送一些等同于 unset 的值(例如布尔值 false 或空字符串)。如果您想检查 _POST 是否确实包含 subDir 键,请显式使用 array_key_exists(出于同样的原因,在 Javascript 中您有时会使用 hasOwnProperty)。
最后,由于你使用单个文件,你必须考虑到第一次打开文件时,_POST会为空,所以你会开始显示“失败”!您已经开始使用 _POST 修复此问题:
- _POST 表示这是一个 AJAX 调用
- _GET表示这是signage.php的正常打开
所以你会做这样的事情:
<?php // NO HTML BEFORE THIS POINT. NO OUTPUT AT ALL, ACTUALLY,
// OR $.post() WILL FAIL.
if (!empty($_POST)) {
// AJAX call. Do whatever you want, but the script must not
// get out of this if() alive.
exit(); // Ensure it doesn't.
}
// Normal _GET opening of the page (i.e. we display HTML here).
更可靠的检查方法是使用辅助功能验证请求的 XHR 状态,例如:
/**
* isXHR. Answers the question, "Was I called through AJAX?".
* @return boolean
*/
function isXHR() {
$key = 'HTTP_X_REQUESTED_WITH';
return array_key_exists($key, $_SERVER)
&& ('xmlhttprequest'
== strtolower($_SERVER[$key])
)
;
}
现在你会:
if (isXHR()) {
// Now you can use both $.post() or $.get()
exit();
}
实际上您可以将 AJAX 代码卸载到另一个文件中:
if (isXHR()) {
include('signage-ajax.php');
exit();
}