How to make a JSONP request from Javascript without JQuery?

后端 未结 12 1419
遇见更好的自我
遇见更好的自我 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: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 )
        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' );
    

提交回复
热议问题