[英]Using jQuery validate to upload a form, using ajax in the submitHandler()… not working
我正在使用表單的jquery驗證。 我想使用ajax提交表單。 當我把ajax調用放在validate的submitHandler()時瀏覽器掛起。 這是怎么回事?
啟用validate方法調試時得到的錯誤消息是:
未捕獲的異常:[Exception ...“WrappedNative原型對象上的非法操作”nsresult:“0x8057000c(NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)”location:“JS frame :: http://ajax.googleapis.com/ajax/libs/jquery/1.4.2 /jquery.min.js :: f :: line 132“data:no]
這對我來說太神秘了。
一些代碼:
$(document).ready(function() {
$("#loginForm").validate({
debug: true,
errorLabelContainer: $('div.error'),
wrapper: 'li',
rules: {
last_name: {
required: true
}
},
messages: {
last_name: {
required: "Please enter your last name."
}
},
submitHandler: function(form){
$.ajax({
type: "POST",
url: "test.php",
data: form,
success: function(msg){
console.log( "Data Saved: " + msg );
},
error: function(msg){
console.log( "Error: " + msg);
}
});
}
});
});
形式是一種非常香草的形式。 通過標准POST提交工作正常。 此外,驗證工作正常...它只是提交與ajax部分失敗了我。
您可能希望在發送之前序列化該表單 - 您可能不希望發送DOM對象
編輯RE:注釋 - 僅選擇一些輸入並序列化 -
$(form).find(":input[name=inp1] :input[name=inp2]").serialize()
用php函數調用ajax方法
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
class Ajax{
public function submitForm($data=array()){
//form - name attribute
//do - ajax page do_
// get - ajax result
return '<script language="javascript" type="text/javascript">
$(document).ready(function (data){
$(\'form[name='.$data['form'].']\').validate({
submitHandler: function(form) {
$.ajax({
method : \'post\',
url : \'' . AJAX_PATH . ''. $data['do'].'\',
data : $(this).serialize(),
dataType : \'html\',
success : function(data){
$(\'form[name='.$data['form'].']\').slideUp(1000);
$(\''. $data['get'] .'\').html(data).fadeIn(1000);
//$(\''. $data['get'] .'\').html(data).fadeIn(1000);
},
error : function(data) {alert(\'missing file\'); }
});
return false;
}
});
});
</script>';
}
}
$ajax = new Ajax();
<?php echo $ajax->submitForm(array('do'=>'do_register.php','form'=>'register','get'=>'#message'));?>
只是詳細說明tobyodavies的答案。 您可能希望將提交更改為
$.ajax({
type: "POST",
url: "test.php",
data: $(form).serialize(),
success: function(msg){
console.log( "Data Saved: " + msg );
},
error: function(msg){
console.log( "Error: " + msg);
}
});
ajax函數期望數據選項是一個字符串(不完全正確,但對於這種情況,它很好),而你傳遞表單dom對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.