jQuery AJAX jsonp return response after done

时间:2017-05-16 09:32:05

标签: javascript jquery ajax class jsonp

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

1 个答案:

答案 0 :(得分:1)

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