这是我第一次使用JSON。我正在尝试使用ajax从PHP脚本获取JSON数据。但是我收到此错误“Error.Parsing JSON请求失败”“未定义”。帮助我这是我的PHP脚本测试.PHP
$data='{
"one": "One",
"two": "Two",
"three": "Three"
}';
header('Content-type: application/json');
echo json_encode($data);
在这里我得到数据 getdata.php
var sURL = 'http://www.example.com/test.php';
$.ajax({
type: "GET",
url:sURL,
dataType:"jsonp",
crossDomain:true,
data: {transid:trans_id , bookingdate: dateVal, bookingtime: timeVal, People: peopleVal,affiliateid: affiliate },
async: false,
contentType:"application/json; charset=utf-8",
success: function (data){
var result = JSON.parse(data);
alert(result);
},
error: function (x, e) {
if (x.status == 0) {
alert(x.response);
alert(x + " " + e);
alert('You are offline!!\n Please Check Your Network.');
}
else if (x.status == 404) {
alert('Requested URL not found.');
}
else if (x.status == 500) {
alert('Internel Server Error.');
}
else if (e == 'parsererror') {
alert('Error.\nParsing JSON Request failed.' + e.statusText);
alert(x.response);
} else if (e == 'timeout') {
alert('Request Time out.');
} else {
alert('Unknow Error.\n' + x.responseText);
}
}
});
这是我的第一个问题,请原谅任何错误
答案 0 :(得分:2)
在使用jsonp
时,添加回调函数,如下所示
var sURL = 'http://www.example.com/test.php';
$.ajax({
type: "GET",
url:sURL,
dataType:"jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallback",
crossDomain:true,
data: {transid:trans_id , bookingdate: dateVal, bookingtime: timeVal, People: peopleVal,affiliateid: affiliate },
async: false,
contentType:"application/json; charset=utf-8",
success: function (data){
var result = JSON.parse(data);
alert(result);
},
error: function (x, e) {
if (x.status == 0) {
alert(x.response);
alert(x + " " + e);
alert('You are offline!!\n Please Check Your Network.');
}
else if (x.status == 404) {
alert('Requested URL not found.');
}
else if (x.status == 500) {
alert('Internel Server Error.');
}
else if (e == 'parsererror') {
alert('Error.\nParsing JSON Request failed.' + e.statusText);
alert(x.response);
} else if (e == 'timeout') {
alert('Request Time out.');
} else {
alert('Unknow Error.\n' + x.responseText);
}
}
});
function jsonpcallback(rtndata) {
alert(rtndata.one);
}
在PHP中生成$data as array
,然后使用json_encode()
返回回调。
$data=array(
"one"=>"One",
"two"=>"Two",
"three"=>"Three"
);
header('Content-type: application/json');
echo $_GET['callback']. '('. json_encode($data) . ')';
答案 1 :(得分:0)
更改您的
dataType:"jsonp",
到
dataType:"json",