[英]Post issue with jQuery and AJAX
On a page called test.html I want to retrieve some JSON data from a page called test2.php by jquery ajax. 在一个名为test.html的页面上,我想通过jquery ajax从一个名为test2.php的页面中检索一些JSON数据。
the following code does not work 以下代码不起作用
test.html: test.html:
$.ajax({
url:"test2.php",
type:"POST",
dataType: "json",
success: function(data){
alert(data.b.d);
}
});
test2.php: test2.php:
<?php
$c= '{"a":{"d":6994,"e":20003,"f":7968,"g":12505,"h":6814},"b":{"d":10623,"e":3404,"f":405,"g":17066,"h":24219}}';
echo $c;
?>
Your test2.php does not contain the proper headers. 您的test2.php没有包含正确的头文件。 Add this just after 在此之后添加
header('Content-type: application/json');
我建议使用Firebug之类的JS调试工具检查您的请求是否返回有效的响应。
If you are aren't sending any data with the request, you probably don't need to use POST. 如果您不随请求发送任何数据,则可能不需要使用POST。 You can just GET instead. 您可以改为GET。 There's even a useful shorthand method: 甚至还有一个有用的速记方法:
$.get("test2.php", function(data) {
// handle your data here
}, 'json');
In test2.php
you are doing things the hard way. 在test2.php
您正在艰难地工作。 Instead of trying to build a JSON string, just build the data structure you want to send to the client. 无需构建JSON字符串,只需构建您要发送给客户端的数据结构即可。 Then encode it with json_encode()
. 然后使用json_encode()
对其进行编码。 You should send the JSON content-type header, so jQuery knows how to decode the data: 您应该发送JSON内容类型标头,因此jQuery知道如何解码数据:
$c = array(
'a'=>array(
'd' =>6994,
'e' => 2003,
'f' => 7968,
)
// and so on...
);
header('content-type: application/json');
echo json_encode($c);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.