preface

Hi, I’m Tom. I wrote a blog about JSONP requests, outlining the concepts and usage of JSONP.

Portal:One minute to finish the JSONP request, the interview full score answer ヾ(≧▽≦*)o

This post is a supplement to the previous post and gives you a more visual understanding of JSONP requests through code

Train of thought

Here is:

Key points:

  • At the end of each request, you must flush out the unwanted methods and tags that are generated
  • Wrap it as a Promise object and use it just like Axios
  • Automatically generates the receive function, without the user thinking about it, all we need to do is pass the value back

Code implementation

Without further ado, let’s start with the code

function myJsonp(options) {
	return new Promise((resolve, reject) = > {
                // Determine if it is the first JSONP request
		if (!window.jsonpNum) {
			window.jsonpNum = 1
		} else {
			window.jsonpNum++
		}

		let {					
			url,
			data,
			timeout = 5000,
			cbkey = 'callback',
		} = options
        
		// Ensure that the method is not repeated each time a request is received
		let funName = 'jsonpReceive' + window.jsonpNum
        
		// Clear some of the garbage generated by the jSONP request
		function clear() { 							
			window[funName] = null
			script.parentNode.removeChild(script);
			clearTimeout(timer)
		}
		
                // Define the jSONP receiver function
		window[funName] = function(res) {
                        // Once the function is executed, the request is successful
			resolve(res) 							
			clear()
		}
		
                // Request a timeout timer
		let timer = setTimeout((a)= > {				
			reject('Out of time')
			clear()
		}, timeout)
		
                // Define the parameters of the request
		let params = ' ' 								
		
                // If there are parameters
		if (Object.keys(data).length) { 			
			for (let key in data) {
				params += ` &${key}=The ${encodeURIComponent(data[key])}`;
			}
			
			params = params.substr(1)}// Concatenate the final request path, ending with the method name of the concatenate callback
		url = url + '? ' + params + ` &${cbkey}=${funName}`  	

		let script = document.createElement('script');
		script.src = url;
		document.body.appendChild(script); })}Copy the code

call

  • Test JSONP interface of QQ music to obtain round broadcast map of home page

    let options = {
    	url:'https://c.y.qq.com/musichall/fcgi-bin/fcg_yqqhomepagerecommend.fcg'.cbkey: 'jsonpCallback'.data: {
    		g_tk: 1928093487.inCharset: 'utf-8'.outCharset: 'utf-8'.notice: 0.format: 'jsonp'.platform: 'h5'.uin: 0.needNewCode: 1
    	},
    	// QQ music interface Jsonp field
    }
    
    myJsonp(options)
    .then(res= > {
    	console.log(res);
    },err=>{
    	console.log(err)
    })
    Copy the code
  • The results of