谁能帮我找到好的教程php/jquery/ajax表单提交验证每个字段从php代码(服务器端验证)。我在网上看过很多教程,但大多数都是将验证错误作为一个组来显示。我希望每个错误都显示在结果的表单字段旁边。我尝试使用php数组传递结果到ajax使用json…但是这行不通。
任何帮助都太好了。
我建议使用JSON,它是专门为AJAX设计的。
服务器端:
$form_fields = array(); // Holds errors in the form
$form_fields['field1'] = true;
$form_fields['field2'] = 'Error bla bla';
header('Content-type: application/json');
echo json_encode($form_fields);
和javascript中的
// put into "data" the response from the server
var responseObj = $.parseJSON(data);
// Check field1
if(responseObj.field1 === true) alert("Field1 is valid!");
else alert('Field1 is not valid: "'+responseObj.field1+'"!');
// Check field2
if(responseObj.field2 === true) alert("Field2 is valid!");
else alert('Field2 is not valid: "'+responseObj.field2+'"!');
你可以随心所欲地构建它,你可以在服务器端为json对象添加更多的值,或者按照你想要的方式构建它。
服务器端将生成如下字符串:{"field1":true,"field2":"错误"}
这实际上是javascript,然后在javascript端浏览器将字符串解码为javascript对象。