[英]retrieve data using json and jquery ajax call no work
I'm triyng to retrieve JSON format data using $.ajax
method of jquery from a php page, I get this error parseerror
when the code runs, but if I see the response of the server with firebug it's Ok. 我正在尝试使用php页面中jquery的$.ajax
方法检索JSON格式的数据,当代码运行时出现此错误parseerror
,但是如果我看到带有萤火虫的服务器的响应就可以了。
Here's my script code: 这是我的脚本代码:
$.ajax({
url: "php/selectedObjectRequest.php",
type: "POST",
dataType: 'json',
data: {},
success: function(data) {
var prova = jQuery.parseJSON(data);
alert(prova.museum);
},
error: function(jqXHR,textStatus,errorThrown) {
alert(textStatus);
}
});
And that's my server side code: 那是我的服务器端代码:
$arrayToEncode = array(
'museum' => 'bellearti',
'atwork' => 'davide',
'beaconCode' => '78888',
'qrCode' => '2252222'
);
echo json_encode($arrayToEncode);
How I can solve? 我该如何解决?
solved: 解决了:
My error was an echo
to test before echo json_encode($arrayToEncode);
我的错误是一个echo
之前测试echo json_encode($arrayToEncode);
pay attention. 请注意。
The parameter data
in your success
handler will be preprocessed because you told jQuery that the dataType
was JSON. success
处理程序中的参数data
将被预处理,因为您告诉jQuery dataType
是JSON。 You should be able to just use data.museum
. 您应该可以只使用data.museum
。 To make sure, console.log(data);
为了确保, console.log(data);
to see what it is. 看看它是什么。
the answer is: change prova.museum to data.museum 答案是:将prova.museum更改为data.museum
$.ajax({
url: "php/selectedObjectRequest.php",
type: "POST",
dataType: 'json',
data: {},
success: function(data) {
alert(data.museum); // add data.museum instant of prova.museum
},
error: function(jqXHR,textStatus,errorThrown) {
alert(textStatus);
}
});
Change the format 变更格式
$arrayToEncode[] = array(
'museum' => 'bellearti',
'atwork' => 'davide',
'beaconCode' => '78888',
'qrCode' => '2252222');
echo json_encode($arrayToEncode, JSON_UNESCAPED_UNICODE);
So that you can call the return value like 这样您就可以像这样调用返回值
for (var j = 0; j < data.length; j++) {
console.log(data[j].museum);
console.log(data[j].atwork);
console.log(data[j].beaconCode);
console.log(data[j].qrCode);
}
Try using this: 尝试使用此:
var parsed = JSON.parse(data);
This usually works for me. 这通常对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.