2016-04-29 103 views
1

我不知道爲什麼不工作...我使用$.ajax運行file.php並通過它(POST)輸入值 此文件.PHP工作,但我的AJAX功能不起作用:成功ajax:如果是200狀態代碼運行功能其他功能

 $.ajax({ 
      type: 'POST', 
      url: 'file.php', 
      data: { email: $('#andressemail').val() }, 
      success: function(data,status){ 
       if(status === '200'){ 
        newmessage(); 
       } 
       else{ 
        erroremessage(); 
       } 
      } 
     }); 

     funtion newmessage(){ 
     alert('ok'); 
     } 

     funtion erroremessage(){ 
     alert('no'); 
     }  

的file.php工作正常(它在我的通訊增加了一個用戶),但$.ajax不起作用,狀態碼是不是200

爲什麼?

+0

試試這個:status =='success' –

回答

3

嘗試以下操作以獲取狀態代碼,使用xhr.status爲的StatusCode:

$.ajax({ 
     type: 'POST', 
     url: 'file.php', 
     data: { email: $('#andressemail').val() }, 
     success: function(xml, textStatus, xhr) { 
      alert(xhr.status); 
      if(xhr.status === '200'){ 
       newmessage(); 
      } 
      else{ 
       erroremessage(); 
      } 
     } 
    }); 

    funtion newmessage(){ 
    alert('ok'); 
    } 

    funtion erroremessage(){ 
    alert('no'); 
    }  
+0

你的代碼是上帝,但是「xhr.status === 200」(不是'200')否? – Borja

+0

是的......你有沒有提醒xhr.status,哪個值會在失敗時返回? –

+1

使它成爲:xhr.status === 200 –

1

成功函數只有在HTTP響應已經200運行。您還需要使用錯誤函數以及在HTTP響應未正確完成時觸發。改變你的代碼看起來像:

function newmessage(data, textStatus, jqXHR){ 
    alert('ok'); 
} 

function erroremessage(data, textStatus, jqXHR){ 
    alert('no'); 
} 

$.ajax({ 
    type: 'POST', 
    url: 'file.php', 
    data: { email: $('#andressemail').val() }, 
    success: newmessage, 
    error: erroremessage 
}); 
0

處理$.ajax最好的辦法是這樣的:

var _ajax = function(url, data, type){ 
    return $.ajax({ 
     type: type, 
     url: url, 
     data: data, 
    }); 
} 

var data = { email: $('#andressemail').val() }; 

_ajax('file.php', data, 'POST') 
    .success(function(res, statusTitle, xhr){ 
     // res: response from server 
     // statusTitle = 'success', ... 
     // xhr: XHR object, for your case, xhr.status will be 200 
    }); 

可以使用.error(function(){...})太,(也.done);