Method of encapsulating jsonp request data

What is jsonp:

Jsonp(JSON with Padding) is a "usage mode" of json, which allows web pages to obtain information from other domain names (websites), that is, cross-domain reading of data.

Why do we need a special technology (JSONP) to access data from different domains? This is because of the homology strategy.

Homologous Policy, a well-known security policy proposed by Netscape, is now used by all JavaScript-enabled browsers.

 

Learn about jsonp's api:

 

 

The method of encapsulating jsonp:

//jsonp.js file

import originJsonp from 'jsonp' //First introduced jsonp //First parameter url For interface address. // Second parameter data The parameters that are carried after the interface address. because jsonp Direct transfer of an object is not supported. So, we can url Separate from the parameters that need to be passed. This makes it easier for us to call this method. // Third parameter opts Corresponding api Above opts export default function jsonp(url, data, opts) { //Splicing url And the parameters to be passed data. //First judge url Are there any in the back??No. If not, add it after?,Some words are added after& url += (url.indexOf("?") < 0 ? "?" : "&") + param(data); //jsonp We need to return a function of promise return new Promise((resolve, reject) => { originJsonp(url, opts, (err, data) => { if (!err) { resolve(data) } else { reject(err) } }) }) }
//Encapsulate a method to splice objects together url Behind export function param(data) { let url = ""; for (var k in data) { //If data[k]by undefined If so, return to empty. let value = data[k] !== undefined ? data[k] : ""; //We use encodeURIComponent() Yes URI Coding url += `&${k}=${encodeURIComponent(value)}`; } //If url If it's not empty, you need to delete the first one.&. return url ? url.substring(1) : ""; }

 

 

Usage method:

//Introducing jsonp method just encapsulated
import jsonp from './jsonp.js'

getData() { const url
= "http://xxxxxxxx"; const data = { name: 'zhangsan', age: 12 }; const opts = { param: 'jsonpCallback' }; jsonp(url, data, opts).then(res => { if (res.code === 0) { console.log(res.data); } }) }

Tags: Javascript JSON

Posted on Wed, 09 Oct 2019 09:32:24 -0700 by seek