我在下面我的jquery脚本遇到麻烦,这是一个基本的删除版本,甚至它将无法正常工作,我有jQuery脚本调用的PHP文件,我已经设置编码并显示一个json响应
然后在jquery脚本中,它应该读取值并回应它,但是没有得到响应。
json.response是错误的方法来调用名称响应的json字符串中的变量吗?
有人可以帮助我卡住
<?PHP
header('Cache-Control: no-cache,must-revalidate');
header('Expires: Mon,26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
// set to retunr response=error
$arr = array ('resonse'=>'error','comment'=>'test comment here');
echo json_encode($arr);
?>
//the script above returns this:
{"response":"error","comment":"test comment here"}
<script type="text/javascript">
$.ajax({
type: "POST",url: "process.PHP",data: dataString,dataType: "json",success: function (data) {
if (json.response == 'captcha') {
alert('captcha');
} else if (json.response == 'error') {
alert('sorry there was an error');
} else if (json.response == 'success') {
alert('sucess');
};
}
})
</script>
更新;
我变了
json.response
成
data.response
但这并没有使它成为ork
解决方法
这是脚本,重写以使用上面的建议和更改您的无缓存方法。
<?PHP
// Simpler way of making sure all no-cache headers get sent
// and understood by all browsers,including IE.
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r',0));
header('Content-type: application/json');
// set to return response=error
$arr = array ('response'=>'error',success: function (data) {
if (data.response == 'captcha') {
alert('captcha');
} else if (data.response == 'success') {
alert('success');
} else {
alert('sorry there was an error');
}
}
}); // Semi-colons after all declarations,IE is picky on these things.
</script>
这里的主要问题是您在返回的JSON(“resonse”而不是“response”)中输入了错字,这意味着您在JavaScript代码中查找错误的属性。将来会遇到这些问题的一种方法是console.log的数据值,并确保您正在寻找的属性在那里。
Learning how to use the Chrome debugger tools(或Firefox / Safari / Opera / etc中的类似工具)也将是无价的。