2012-08-17 39 views
0

使用jquery時可以識別頁面返回的內容嗎?我在這裏提交表單使用jquery這樣的:識別使用jQuery提交表單時返回的內容

$("#sform").submit(function() { 
    $.ajax({ 
     type: "POST", 
     data: $(this).serialize(), 
     cache: false, 
     url: "user_verify.php", 
     success: function(data) { 
      $("#form_msg").html(data); 
     } 
    }); 
    return false; 
}); 

的user_verify.php頁面不其一貫的核查工作,並返回錯誤信息或成功將用戶添加到數據庫。如果它的錯誤是一堆錯誤信息,或者它的成功通常是「您已成功註冊」。如果錯誤消息返回或成功消息,我可以以某種方式識別使用jQuery。這樣,如果它的錯誤我可以在表單中使用該數據,或者如果它的成功,我可以關閉表單並顯示成功消息。

+0

我注意到,有一個問題,你的碼。看看這一行: data:$(this).serialize(), 在$ .ajax jquery方法中,「this」綁定到全局窗口對象,而不是$('#sform') – sudip 2012-08-17 14:08:00

回答

1

是的,那就是:

success: function(data) { 
    $("#form_msg").html(data); 
} 

你可以在任何你想要的方式操縱data。您可以在success函數返回從服務器端和處理數據的JSON(使用dataType)編碼字符串

success: function(data) { 
    if(data->success == 'ok'){ 
     // hide the form, show another hidden div. 
    } 
} 

所以user_verify.php應打印例如:

// .... queries 
$dataReturn = array(); 
$dataReturn['success'] = 'ok'; 
$dataReturn['additional'] = 'test'; 
echo json_encode($dataReturn); 
die; // to prevent any other prints. 
+0

'ok'來自user_verify.php頁面的權利? – Norman 2012-08-17 13:43:45

+0

是的,你作爲JSON返回,讓我修改我的答案 – 2012-08-17 13:44:26

0

你可以,如果你的PHP返回0錯誤所以你做這樣的事情裏面

success: function(data) { 
     if(data==0){ 
     //do error procedure 
     }else{ 
     //do success procedure 
     } 
    } 

希望這有助於

0

你可以做的,是這樣的:

$.ajax({ 
type:"POST", //php method 
url:'process.php',//where to send data... 
cache:'false',//IE FIX 
data: data, //what will data contain 
//check is data sent successfuly to process.php 
//success:function(response){ 
//alert(response) 
//} 
success: function(){ //on success do something... 
$('.success').delay(2000).fadeIn(1000); 
//alert('THX for your mail!'); 
} //end sucess 
}).error(function(){ //if sucess FAILS!! put .error After $.ajax. EXAMPLE :$.ajax({}).error(function(){}; 
alert('An error occured!!'); 
$('.thx').hide(); 
}); 
//return false prevent Redirection 
    return false; 
}); 
0

可以checke在「成功」回調函數「數據」參數。 我注意到你的代碼存在問題。看這句話:

data: $(this).serialize(), 

在$阿賈克斯jQuery的方法「這種」被綁定到全局窗口對象,而不是$(「#sform」)