我已经研究过许多SO问题并遵循那些回答的建议,包括this post,但我仍然在努力让这个问题发挥作用。我准备了一个简化的测试。
JS& HTML
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(function () {
data = {};
data.subject = "Change the subject";
/*
$.post('php/test.php', { jsonData: JSON.stringify(data) }, function (response) {
console.log($(response).html());
});
*/
$.ajax({
url: 'php/test.php',
data: data,
contentType: 'application/json',
cache: false
}).done(function (result, success, xhr) {
console.log("result=" + result);
}).fail(function (xhr, desc, err) {
var msg = "Send mail - " + "\nError: " + "\n" + xhr.responseText;
console.log(msg);
});
});
</script>
</head>
<body>
<form id="form" name= "form" >
<input id="subject" name="subject" value="not a subject" />
</form>
</body>
</html>
PHP
修改
我将$ _POST更改为$ _REQUEST - 没有帮助
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
/*
$arr=json_decode($_POST['jsonData']);
echo $arr[0]['id'];
print_r($arr);
*/
if (!isset($_POST["subject"]) || empty(trim($_POST["subject"])))
throw new Exception('A subject is required.');
else $subject = filter_var(trim($_POST["subject"]), FILTER_SANITIZE_STRING);
echo "subject=" . $subject;
的console.log
test.html:22结果=
(!)致命错误:未捕获的异常 消息'需要主题'的'例外'。在 /home/deje/public_html/writers-tryst/php/test.php在线 12 (!)例外:需要主题。在 /home/deje/public_html/writers-tryst/php/test.php在线 12 调用堆栈#TimeMemoryFunctionLocation 10.0003248416 {main}()... / test.php : 0
Addional error_log:
[10-May-2016 01:50:45 UTC] PHP致命错误:未捕获的异常 消息'需要主题'的'例外'。在 /home/deje/public_html/writers-tryst/php/test.php:12堆栈追踪:
在第12行的/home/deje/public_html/writers-tryst/php/test.php中抛出0 {main}
修改
网络表:
答案 0 :(得分:1)
method
的默认$.ajax
为GET
,更改为POST
$.ajax({
url: 'php/test.php',
data: data,
method: 'post',
cache: false
}).done(function (result, success, xhr) {
console.log("result=" + result);
}).fail(function (xhr, desc, err) {
var msg = "Send mail - " + "\nError: " + "\n" + xhr.responseText;
console.log(msg);
});
答案 1 :(得分:0)
在test.php中
$subject = array();
$subject[] = 'assign values';
echo json_encode($subject);