2014-09-04 101 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) {} 
});