我正在尝试通过AJAX jQuery发布表单。它指向的PHP脚本返回一个JSON编码数组。但是,在主页JSON.parse()
上的接收端无效。
如果我在某些需要包含的文件类型中缺失
,请提供建议这是我的代码。
< script type = "text/javascript" >
$(document).ready(function() {
$("#send").submit(function() {
//$("#submit_form").html('');
$("#modal-text2").html("<img src=" + "img/loader1.gif "
+ "/></br</br><h4>DATA VALIDATION IN PROCESS !!! PLEASE WAIT</h4>");
$("#myModal2").modal('show');
$.post($("#send").attr("action"), $("#send").serialize(), function(data) {
var decode = JSON.parse(data);
if (decode.err > 0) {
alert("Hi");
}
});
//Important. Stop the normal POST
return false;
});
});
< /script>
&#13;
PHP脚本发回的JSON编码数组是:
{"err":8,"er1":1,"er3":1,"er4":1,"er5":1,"er6":1,"er7":1,"er8":1,"er9":1,"error1":"First Name is Required","error3":"Last Name is Required","error4":"Email is Required","error5":"Please Select a Gender","error6":"Date of Birth is Required","error7":"Mobile No is Required","error8":"Password is Required","error9":"Please Fill The Captcha"}
答案 0 :(得分:0)
不知道它是否是导致问题的原因,或者它只是一个错字在这里,但你在下面的行中有一个拼写错误:
<img src="+"img/loader1.gif "+"/></br</br>
你没有关闭第一个换行符,并且斜杠应该在br之后 - 也不确定为什么你在那个html块中有这么多的quuotes - 它应该是:
$("#modal-text2").html("<img src='img/loader1.gif'/><br/><br/><h4>DATA VALIDATION IN PROCESS !!! PLEASE WAIT</h4>")
答案 1 :(得分:0)
data
值是否有任何问题。如果JSON.parse中发生错误,请使用try / catch来捕获消息。
try {
var decode = JSON.parse(data);
}catch(e){
console.log(e) ;
}
确保您的php以正确的方式响应json。或者可能有一些看不见的角色并提出问题。
<?php
$data = ... ;
header('Content-type:application/json;charset=utf-8');
echo json_encode($data) ;
?>
答案 2 :(得分:0)
我认为你的脚本中有一个sytax错误,只需在脚本的最后一行检查&lt;的结束标记。 /脚本&GT;有空间,删除它并尝试 -
</script>
我执行你的代码的解析片段,它正常工作。
var data = '{"err":8,"er1":1,"er3":1,"er4":1,"er5":1,"er6":1,"er7":1,"er8":1,"er9":1,"error1":"First Name is Required","error3":"Last Name is Required","error4":"Email is Required","error5":"Please Select a Gender","error6":"Date of Birth is Required","error7":"Mobile No is Required","error8":"Password is Required","error9":"Please Fill The Captcha"}';
var decode = JSON.parse(data);
if (decode.err > 0) {
alert("Hi");
}