封裝原生jsonp請求
阿新 • • 發佈:2019-02-02
如有錯誤,歡迎指正
看這篇文章的小夥伴應該已經瞭解了最基本的jsonp請求了,如果不瞭解,請檢視我另一篇文章。或者百度一下。
這裡直接上封裝程式碼:
html程式碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id="dv"></div> <script> function jsonp(obj) { //寫入url地址中的函式名稱,動態建立 var callbackName = 'jsonp_callback_' + Date.now() + Math.random().toString().substr(2, 5); //建立一個script標籤 var scriptObj = document.createElement("script"); obj.parames = obj.parames || ''; if (typeof obj.parames == 'object') { var arr = new Array(); for (var key in obj.parames) { arr.push(key + '=' + obj.parames[key]) } obj.parames = arr.join('&'); } //設定標籤的請求路徑 //像這樣:http://localhost:3000/api?callback=jsonp_callback_153498520409635392&id=1 scriptObj.src = obj.url + '?' + 'callback=' + callbackName + '&' + obj.parames; //將建立好的帶請求的script標籤新增到html的body中 document.body.appendChild(scriptObj); //這裡必須這樣寫window[callbackName]; //如果寫window.callbackName會報錯沒有定義 window[callbackName] = function (res) { obj.success(res); //刪除的時候可以這樣寫 //由於請求一次會建立一個script標籤和一個函式,所以每次獲取到結果後就刪除 delete window.callbackName; document.body.removeChild(scriptObj); } } </script> <script> jsonp({ //請求地址 url:'http://localhost:3000/api', //請求引數,物件 parames:{ id: 1 }, //成功回撥 success:function (res) { console.log(res) } }) </script> </body> </html>
後端express程式碼:
var express = require("express") var app = express() // app.all('*', function (req, res, next) { // //設定跨域 // res.header("Access-Control-Allow-Origin", "*"); // next();//不能省略 // }) app.get('/api', function (req, res) { var data={ name: "王八", age: 100 } //返回的型別必須設定為javascript res.type('text/javascript') //前端路由中的引數獲取,req.query。 console.log("query",req.query); res.send(req.query.callback+'(' +JSON.stringify(data)+')') //這裡的資料必須轉化為字串,否則傳入一個物件瀏覽器無法解析 // res.send(req.query.callback+'(' +data+')') }) app.listen(3000) console.log("listen the port 3000");
如果感覺原生太複雜的,可以檢視jquery官方封裝的ajax中封裝的jsonp請求。