我想通过 jQuery 发送数据 ajax
函数调用 PHP 脚本并接收响应 - 成功或失败。我正在使用的代码:
JavaScript:
$.ajax({
type: 'POST',
url: 'foo.php',
dataType: 'json',
data: {
foo: 'foo'
},
success: function (response) {
...
},
error: function (response) {
...
}
});
PHP:
<?php
header("Content-Type: text/json");
echo $_POST['foo']
?>
但是这总是返回错误,因为 header("Content-Type: text/json");
.
这里做错了什么?
最佳答案
这将在服务器端正确处理错误。
<?php
if(isset($_POST['foo']){
header('Content-Type: application/json');
$foo = array(
"foo" => $_POST['foo'];
);
echo json_encode($foo);
} else {
header('HTTP/1.0 400 Bad Request');
}
?>
关于javascript - 将 JSON 从 jQuery 发送到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45399731/