我尝试使用简单的 AJAX客户端发布JSON,并使用php作为 restful server 。但是我正在解析这个json它显示错误。
错误:" parsererror","没有从文本转换为application / json"
我的客户端代码是,
<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#driver").click(function(event){
var person = {
name: 'df',
};
$.ajax({
url: './ajax.php',
dataType: "application/json",
//contentType: "json",
type:'post',
data: person,//{'FirstName':FirstName,'LastName':LastName},
success: function(msg) {
alert(msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
});
});
</script>
</head>
<body>
<div id="stage" style="background-color:cc0;">
STAGE
</div>
<input type="button" id="driver" value="Load Data" />
</body>
</html>
我的服务器代码是,
<?php
if ($_SERVER['REQUEST_METHOD'] == "GET") {
} else if ($_SERVER['REQUEST_METHOD'] == "POST") {
header('Content-type: application/json');
$jsonData = file_get_contents('php://input');
echo $jsonData;
//echo "true";
}
?>
答案 0 :(得分:1)
将exit
放在逻辑的末尾,尝试以下方法:
<?php
if ($_SERVER['REQUEST_METHOD'] == "GET") {
...
} else if ($_SERVER['REQUEST_METHOD'] == "POST") {
header('Content-type: application/json');
$jsonData = file_get_contents('php://input');
echo $jsonData;
//echo "true";
exit;
}
?>