简体   繁体   中英

jQuery AJAX jsonp return response after done

Its similar question from here How do I return the response from an asynchronous call?

in Ajax JSONP, how do i get the response after done?

https://jsfiddle.net/zerolfc/svwxm5tt/

class Api {

    constructor() {

    }

    yahoo(query) {

    }

    jsfiddle(query){

        let result = '';

        $.ajax({
            url: 'https://jsfiddle.net/echo/jsonp/',
            dataType: 'jsonp',
            jsonpCallback: 'jsonp',
            data: {
              query: 'query',
              format: 'json'
            },
        }).done(function(response) {
            result = response;
            console.log(result);
        });

        return result;

    }

}

$api = new Api;

console.log( $api.jsfiddle() ); // empty

The JSONP "protocol" relies on the site replying to your request with a JavaScript statement of the form,

 someFunction( someJSON )

The name of the function is supplied as an argument from your code, with the idea being that the response script, once consumed and interpreted by the browser, will result in a call to that function with a parsed blob of JSON — which is to say, a JavaScript object. The jQuery library will do some of the bookeeping work for you, even to the extent of creating the globally-scoped function to call (which will be code that just calls the callback you supply as the "success" argument).

Example

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