How to make a JSONP request from Javascript without JQuery?

后端 未结 12 1286
遇见更好的自我
遇见更好的自我 2020-11-22 17:27

Can I make a cross-domain JSONP request in JavaScript without using jQuery or other external library? I would like to use JavaScript itself and then parse the data and make

相关标签:
12条回答
  • 2020-11-22 17:46

    Lightweight example (with support for onSuccess and onTimeout). You need to pass callback name within URL if you need it.

    var $jsonp = (function(){
      var that = {};
    
      that.send = function(src, options) {
        var callback_name = options.callbackName || 'callback',
          on_success = options.onSuccess || function(){},
          on_timeout = options.onTimeout || function(){},
          timeout = options.timeout || 10; // sec
    
        var timeout_trigger = window.setTimeout(function(){
          window[callback_name] = function(){};
          on_timeout();
        }, timeout * 1000);
    
        window[callback_name] = function(data){
          window.clearTimeout(timeout_trigger);
          on_success(data);
        }
    
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.async = true;
        script.src = src;
    
        document.getElementsByTagName('head')[0].appendChild(script);
      }
    
      return that;
    })();
    

    Sample usage:

    $jsonp.send('some_url?callback=handleStuff', {
        callbackName: 'handleStuff',
        onSuccess: function(json){
            console.log('success!', json);
        },
        onTimeout: function(){
            console.log('timeout!');
        },
        timeout: 5
    });
    

    At GitHub: https://github.com/sobstel/jsonp.js/blob/master/jsonp.js

    0 讨论(0)
  • 2020-11-22 17:46

    If you are using ES6 with NPM, you can try node module "fetch-jsonp". Fetch API Provides support for making a JsonP call as a regular XHR call.

    Prerequisite: you should be using isomorphic-fetch node module in your stack.

    0 讨论(0)
  • 2020-11-22 17:47
    /**
     * Get JSONP data for cross-domain AJAX requests
     * @private
     * @link http://cameronspear.com/blog/exactly-what-is-jsonp/
     * @param  {String} url      The URL of the JSON request
     * @param  {String} callback The name of the callback to run on load
     */
    var loadJSONP = function ( url, callback ) {
    
        // Create script with url and callback (if specified)
        var ref = window.document.getElementsByTagName( 'script' )[ 0 ];
        var script = window.document.createElement( 'script' );
        script.src = url + (url.indexOf( '?' ) + 1 ? '&' : '?') + 'callback=' + callback;
    
        // Insert script tag into the DOM (append to <head>)
        ref.parentNode.insertBefore( script, ref );
    
        // After the script is loaded (and executed), remove it
        script.onload = function () {
            this.remove();
        };
    
    };
    
    /** 
     * Example
     */
    
    // Function to run on success
    var logAPI = function ( data ) {
        console.log( data );
    }
    
    // Run request
    loadJSONP( 'http://api.petfinder.com/shelter.getPets?format=json&key=12345&shelter=AA11', 'logAPI' );
    
    0 讨论(0)
  • 2020-11-22 17:48
    function foo(data)
    {
        // do stuff with JSON
    }
    
    var script = document.createElement('script');
    script.src = '//example.com/path/to/jsonp?callback=foo'
    
    document.getElementsByTagName('head')[0].appendChild(script);
    // or document.head.appendChild(script) in modern browsers
    
    0 讨论(0)
  • 2020-11-22 17:56

    Please find below JavaScript example to make a JSONP call without JQuery:

    Also, you can refer my GitHub repository for reference.

    https://github.com/shedagemayur/JavaScriptCode/tree/master/jsonp

    window.onload = function(){
        var callbackMethod = 'callback_' + new Date().getTime();
    
        var script = document.createElement('script');
        script.src = 'https://jsonplaceholder.typicode.com/users/1?callback='+callbackMethod;
    
        document.body.appendChild(script);
    
        window[callbackMethod] = function(data){
            delete window[callbackMethod];
            document.body.removeChild(script);
            console.log(data);
        }
    }

    0 讨论(0)
  • 2020-11-22 17:57

    I wrote a library to handle this, as simply as possible. No need to make it external, its just one function. Unlike some other options, this script cleans up after itself, and is generalized for making further requests at runtime.

    https://github.com/Fresheyeball/micro-jsonp

    function jsonp(url, key, callback) {
    
        var appendParam = function(url, key, param){
                return url
                    + (url.indexOf("?") > 0 ? "&" : "?")
                    + key + "=" + param;
            },
    
            createScript = function(url, callback){
                var doc = document,
                    head = doc.head,
                    script = doc.createElement("script");
    
                script
                .setAttribute("src", url);
    
                head
                .appendChild(script);
    
                callback(function(){
                    setTimeout(function(){
                        head
                        .removeChild(script);
                    }, 0);
                });
            },
    
            q =
                "q" + Math.round(Math.random() * Date.now());
    
        createScript(
            appendParam(url, key, q), function(remove){
                window[q] =
                    function(json){
                        window[q] = undefined;
                        remove();
                        callback(json);
                    };
            });
    }
    
    0 讨论(0)
提交回复
热议问题