2014-09-04 111 views
0

我真的不知道爲什麼alertconsole.log未在此代碼被觸發:

  $.post("http://localhost:8080/mail", 
        jsonObject, 
        function(data) { 
        console.log("Done!"); 
         alert("Thank you for your inquiry. We will get back to you soon."); 
         alert("Response: " + JSON.stringify(data)); 
        } 
       ); 

雖然我可以看到郵件API工程,我能得到的電子郵件用我放入HTML表單的值。 alertconsole.log未被觸發可能是什麼原因?

我可以在瀏覽器上的日誌,雖然看到這一點:阻止

跨來源請求:同源策略不允許讀 遠程資源的http://localhost:8080/mail。通過將資源移動到相同的域或啓用CORS,可以修復 。

難道這是原因嗎?如果是的話,我應該怎麼做才能使$.post觸發成功或失敗。

+0

使用回調是是這樣的原因。 *「如果是這樣,我應該怎麼做才能讓$ .post觸發成功或失敗。」*正如消息所示:「可以通過將資源移動到相同的域或啓用CORS來解決此問題。」 – 2014-09-04 15:56:19

+0

如果使用chrome命令行打開:'chromium-browser --disable-web-security' – 2014-09-04 16:10:41

+0

您有一個CORS問題。基本上這意味着你將需要改變你的後端實現來返回正確的頭文件。你可以參考這個[http://stackoverflow.com/questions/5750696/how-to-get-a-cross-origin-resource-sharing-cors-post-request-working](http://stackoverflow.com /問題/ 5750696 /如何到獲得-A-跨域資源共享-CORS-請求後,工作) – arisalexis 2014-09-04 15:58:34

回答

0

跨源請求(CORS)是您的問題。作爲記錄here

如果你想在同一個域強制跨域請求(如JSONP)$.ajax()跨域參數,跨域的值設置爲true。這允許,例如,服務器端重定向到另一個域。

$.ajax({ 
    type: "POST", 
    url: "http://localhost:8080/mail", 
    crossDomain : true, 
    data: jsonObject 
    ... 
}) 

關於如何捕捉成功或失敗:你可以鏈done(), fail(), and always()$.post

$.post("http://localhost:8080/mail", jsonObject, function(data) { 
    // alert("success"); 
}).done(function(){ 
    // alert("success 2"); 
}).fail(function() { 
    // alert("error"); 
}).always(function(){ 
    // alert("finished"); 
}); 

這還與$.ajax()或內$.ajax()

$.ajax(function(){ 
    success: function (responseData, textStatus, jqXHR) {}, 
    error: function (responseData, textStatus, errorThrown) {} 
});