当我使用AJAX调用PHP运行我的小javascript时,它总是返回一个JSON parsererror。
在PHP中我可以看到我的json填充了这样的数组:
json编码:{"Year":"2012","Make":"Ford","Model":"Taurus","Error":"no error"}
This是网站:
当访问者离开左侧的字段VIN时,将调用AJAX,并且应自动填充右侧的3个字段。
function decode_my_vin(myvin) {
alert("javascript began");
dataoneID = '00000';
dataoneKEY = 'x0x0x';
jQuery.ajax(
{
cache: false,
type: 'POST',
url: '/wp-content/themes/Impreza-child/vin-decoder.php',
dataType: "json",
data: {
'value1_VIN': myvin,
'value2_ID': dataoneID,
'value3_KEY': dataoneKEY,
},
success: function(response) {
var resultYear = response.Year;
var resultMake = response.Make;
var resultModel = response.Model;
var resultMessage = response.Message;
alert("success returned: Year " + resultYear + " Make " + resultMake + " Model " + resultModel + " Message " + resultMessage);
document.getElementById("fld_7290902_1").value = resultYear;
document.getElementById("fld_1595243_1").value = resultMake;
document.getElementById("fld_7532728_1").value = resultModel;
document.getElementById("fld_7532728_1").value = resultMessage;
return;
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert("Error in jquery: " + msg);
$('#post').html(msg);
},
complete: function(value) {
alert("returned after complete: " + value);
}
});
}
<?php
header('Content-Type: application/json');
$vinResult = array(
'Year' => '2012',
'Make' => 'Ford',
'Model' => 'Taurus',
'Error' => 'No Error'
);
echo json_encode($vinResult);
?>
答案 0 :(得分:0)
在ajax调用的错误函数中,它为$('#post').html(msg);
说错误函数提供了错误。尝试使用jQuery('#post')
代替$('#post')
。
要解析您的回复,请使用var data = jQuery.parseJSON( response );
,然后按data.Year
等方式访问字段。