简体   繁体   English

使用Jquery进行跨域Ajax调用

[英]Cross-domain Ajax call with Jquery

I've been trying for days to make this work: 我一直在努力使这项工作:

            $.ajax({
                url: 'http://otherdomain.com/mail.json' ,
                dataType: 'json',
                data: jsonObject,
                success: function(data){
                    alert("Thank you for your inquiry. We will get back to you soon.");                     
                }
            });

The mail.json API works when I use the Chrome Postman app to test and the response header is this: 当我使用Chrome Postman应用进行测试时, mail.json API可以正常工作,并且响应标头是这样的:

Accept-Ranges →bytes
Access-Control-Allow-Origin →*
Alternate-Protocol →80:quic,p=0.002
Cache-Control →private
Content-Encoding →gzip
Content-Length →22
Content-Type →application/json; charset=UTF-8
Date →Mon, 15 Sep 2014 05:18:09 GMT
Server →Google Frontend
Vary →Accept-Charset, Accept-Encoding, Accept-Language, Accept

What could be wrong in my Jquery code, as the server works fine. 服务器工作正常,我的Jquery代码可能出了什么问题。

For cross domain ajax calls it is preferable to use JSONP. 对于跨域ajax调用,最好使用JSONP。 You can get more information here: JSONP stackoverflow 您可以在此处获取更多信息: JSONP stackoverflow

As you saied,the page reloads when the form submit button is clicked where this ajax call is in.If using asynchronous submission,you should prvent the default action of browser.For exanple, 如您所说,当单击此ajax调用所在的表单提交按钮时,页面将重新加载。如果使用异步提交,则应采用浏览器的默认操作。例如,

$('submit').click(function(e){
    //prevent default action
    e.preventDefault();
    $.ajax({
       url: ,
       success: function(res) {

       }
    })
})

The URL http://otherdomain.com/mail.json is from another domain. URL http://otherdomain.com/mail.json来自另一个域。 According to the "Same Origin Policy", you should not be able to send the request (Unless you simply open your HTML file in the browser with deploying to a server, something like file:///C:/Projects/HTML5/WebContent/request.html , I guess). 根据“相同来源政策”,您应该无法发送请求(除非您只是简单地在浏览器中打开HTML文件并部署到服务器,例如file:///C:/Projects/HTML5/WebContent/request.html ,我想)。

To make cross-domain Ajax requests, you can try JSONP as @Vivin suggests. 要发出跨域Ajax请求,可以按照@Vivin的建议尝试JSONP。 So your jQuery code could be like this: 因此,您的jQuery代码可能是这样的:

$.ajax({
        url: url,
        dataType: 'jsonp',
        jsonp: 'jsonpcallback',
    }).done(function(data) { // deal with your data
    });

In your server-side, your need to return something like jsonpcallback(YOUR_DATA_IN_JSON_STRING) . 在服务器端,您需要返回类似jsonpcallback(YOUR_DATA_IN_JSON_STRING) For a more detailed tutorial, you can search online. 有关更详细的教程,您可以在线搜索。 Here is a Chinese tutorial written by me: JSONP Tutorial 这是我写的中文教程: JSONP教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM