我正在尝试学习Ajax和Json,所以我可以在它上面构建它以将PHP数据传递到我的网页而不需要刷新。 我使用以下示例,但结果html页面没有显示任何内容。有人可以让我知道我做错了什么。
Html代码
<html>
<body>
<script src="jquery.js"></script>
<script>
$.ajax({
url: "test.php",
dataType: "json", //the return type data is jsonn
success: function(data){ // <--- (data) is in json format
alert(data.test1);
//parse the json data
}
});
</script>
<div id = "data"></div>
</body>
</html>
PHP代码名为test.php
<?php
$test = array();
$test['test1'] = '1';
$test['test2'] = '2';
$test['test3'] = '3';
echo json_encode($test);
//echo nothing after this //not even html
?>
答案 0 :(得分:2)
您需要在php中设置响应内容类型。
我认为jQuery会检查响应类型。
header("Content-Type: application/json");
还为错误添加绑定。
$.ajax({
url: "test.php",
dataType: "json", //the return type data is jsonn
success: function(data){ // <--- (data) is in json format
alert(data.test1);
//parse the json data
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error: " + textStatus);
}
});
答案 1 :(得分:-1)