也許這種方法可以幫助你..它更像是一個暗示比完整的解決方案...
在服務器端,你會做驗證,並返回JSON(例如) - $進步是真/假 - 根據驗證結果和$錯誤是陣列(名稱,translated_error /或 「」)
局部PHP:
$res = array(
'progress' => $progress,
'errors' => $errors
);
$jsonReturn = json_encode($res);
//output result
header('Content-Type: text/html; charset=utf-8');
echo $jsonReturn;
部分的jQuery:
var errorFields = $([]).add(field1_error).add(field2_error).add(field3_error),
mainFields = $([]).add(field1).add(field2).add(field3);
$('#btnPublish').button().click(function(event){
mainFields.removeClass('ui-state-error');
errorFields.val();
$.ajax({
type: 'POST',
url: your_url,
data: $('#your_form_id').serialize(),
async: false,
success: function (returned_value){
var obj = $.parseJSON(returned_value);
if (obj.progress==true){
alert('Validation successfull');
}else{
$.each(obj.errors, function(index, value) {
if (value!=""){ //it will skip those fields with no errors
$('#'+index).addClass(('ui-state-error'));
$('#'+index+'_error').val(value);
}
});
}//end return ajax
}//end ajax
});
});
這裏有什麼用AJAX的好處?如果我正確地做到了這一點,那麼您將使用整個表單的服務器端驗證。它與實際提交頁面和顯示服務器生成的驗證輸出以及表單有什麼不同? – Krab 2010-11-20 11:41:17
原因是我基於選擇的下拉菜單顯示其他字段。如果我正常提交頁面,那些字段將丟失。我相信要解決這個問題比上面要困難得多。 – 2010-11-20 11:54:08