简体   繁体   中英

Retrieve json data with jquery ajax cross domain

I try to retrieve json data from other domain with jquery ajax, but it doesn't work. This is my code:

function getLeague() {
    $.ajax({
        url: 'http://otherdomainurl.ashx?username=xxx&pass=xxx&type=xxx',
        headers: { 'Access-Control-Allow-Origin': '*' },
        dataType: 'jsonp',
        async: false,
        crossDomain: true,
        success: function(data) {
            alert('Success');
        },
        error: function(error) {
            alert('Fail');
        }
    });
}

i've tried to remove header, async, and crossDomain. i've tried to change the dataType to json. But it always give a fail alert. I use django(but i think it's not the problem). Thanks..

This header needs to be on the server side, not client side.

Try Django CORS Headers :

A Django App that adds CORS (Cross-Origin Resource Sharing) headers to responses.

Although JSON-P is useful, it is strictly limited to GET requests. CORS builds on top of XmlHttpRequest to allow developers to make cross-domain requests, similar to same-domain requests.

Your error is at async: false .

Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation

http://api.jquery.com/jquery.ajax/

So. do your really need to set async: false?

Try Below code

function getLeague() {
$.ajax({
    url: 'http://otherdomainurl.ashx',
    data: {Your Obj},
    type: 'GET',
    dataType: 'jsonp',
    success: function(data) {
        alert('Success');
    },
    error: function(error) {
        alert('Fail');
    }
});

}

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