Jquery jsonp response error - Callback was not called

前端 未结 3 820
难免孤独
难免孤独 2021-02-09 07:34

I\'m trying to get some information from a different domain, the domain allows only jsonp call - others get rejected. How can I get the content instead of execution? Because I g

3条回答
  •  北恋
    北恋 (楼主)
    2021-02-09 07:56

    There are a few issues with your $.ajax call.

    $.ajax({
        url: url + '?callback=?',
        // this is not needed for JSONP.  What this does, is force a local
        // AJAX call to accessed as if it were cross domain
        crossDomain: true,
        // JSONP can only be GET
        type: "POST",
        data: {key: key},
        // contentType is for the request body, it is incorrect here
        contentType: "application/json; charset=utf-8;",
        // This does not work with JSONP, nor should you be using it anyway.
        // It will lock up the browser
        async: false,
        dataType: 'jsonp',
        // This changes the parameter that jQuery will add to the URL
        jsonp: 'callback',
        // This overrides the callback value that jQuery will add to the URL
        // useful to help with caching
        // or if the URL has a hard-coded callback (you need to set jsonp: false)
        jsonpCallback: 'jsonpCallback',
        error: function(xhr, status, error) {
            console.log(status + '; ' + error);
        }
    });
    

    You should be calling your url like this:

    $.ajax({
        url: url,
        data: {key: key},
        dataType: 'jsonp',
        success: function(response) {
            console.log('callback success');
        },
        error: function(xhr, status, error) {
            console.log(status + '; ' + error);
        }
    });
    

    JSONP is not JSON. JSONP is actually just adding a script tag to your . The response needs to be a JavaScript file containing a function call with the JSON data as a parameter.

    JSONP is something the server needs to support. If the server doesn't respond correctly, you can't use JSONP.

    Please read the docs: http://api.jquery.com/jquery.ajax/

提交回复
热议问题