近期用wordpress为朋友搭建个网站,其中有个模块需要实现类似于报名的功能,其中根据身份证信息,确定该信息是否已提交,通过ajax实现实时验证,过程中后台返回值出现undefined,折腾了很长时间,最终解决。
function blur_checkidentityNo() { if ($("#identityNo").val()=="") { $("#identityNomsg").text("请输入身份证号").addClass("errorc"); } else { $.ajax({ type: "POST", url: "c" , async:false, data: $('#lqiuzhi').serialize(), success: function (date) { if(date==1){$("#identityNomsg").text("您已登记过信息,如需帮助请联系管理员").addClass("errorc");} else{$("#identityNomsg").text("√").addClass("okc");} }, error : function() { $("#identityNomsg").text("错误").addClass("errorc"); } }); } }
看第9行代码,关键就在此处,原因是Jquery的ajax是异步的,所以大多时候没执行完AJAX就return htmlcontent了,所以会一直返回undefined, 所以只要添加async: false,即修改此方法为同步就可以解决问题了