简体   繁体   中英

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:

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.

For cross domain ajax calls it is preferable to use JSONP. You can get more information here: 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,

$('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. 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).

To make cross-domain Ajax requests, you can try JSONP as @Vivin suggests. So your jQuery code could be like this:

$.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) . For a more detailed tutorial, you can search online. Here is a Chinese tutorial written by me: JSONP Tutorial

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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