How to make a JSONP request from Javascript without JQuery?

后端 未结 12 1430
遇见更好的自我
遇见更好的自我 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

提交回复
热议问题