目標
- 掌握jsonp的原理
- 會搭建node服務器創建jsonp接口
- 學會封裝jsonp
- 學會jsonp的實際運用
知識要點
- 跨域解決
- jsonp原理及封裝
- jsonp服務器搭建
- jsonp實際運用
ajax問題
- 瀏覽器同源策略
- 同源策略是瀏覽器的一個安全功能,不同源的客戶端腳本在沒有明確授權的情況下,不能讀寫對方資源
- 源 :協議、域名和端口號
- 跨域
- 不受同源策略影響的資源的引入
- <script src="..."></script>,<img>,<link>,<iframe>
jsonp
JSONP*(JSON with Padding)解決跨域問題;可以讓網頁從別的域名(網站)那獲取資料,即跨域讀取數據。
- jsonp原理
- 通過script來實現跨域;
- 服務端實現
- jsonp代碼封裝
function ajax(options) { let opts = Object.assign({ method: 'get', url: '', headers: { 'content-type': 'application/x-www-form-urlencoded' }, jsonp:"cb", data: '', success: function () { } }, options) //處理jsonp請求; if(opts.dataType==="jsonp"){ jsonpFn(opts.url,opts.data,opts.jsonp,opts.success); return false; } function jsonpFn(url,data,cbName,cbFn){ // cbName cb/callback let fnName = "KKB_"+Math.random().toString().substr(2); window[fnName] = cbFn; let path = url+"?"+o2u(data)+"&"+cbName+"="+fnName; // console.log(path); let o = document.createElement("script"); o.src = path; document.querySelector("head").appendChild(o); } let xhr = new XMLHttpRequest(); if (options.method == "get") { let data = o2u(opts.data) options.url = options.url + "?" + data; } xhr.open(options.method, options.url, true); for (let key in opts.headers) { xhr.setRequestHeader(key, opts.headers[key]); } let sendData; switch (opts.headers['content-type']) { case 'application/x-www-form-urlencoded': sendData = o2u(opts.data); break; case 'application/json': sendData = JSON.stringify(opts.data); break; } xhr.onload = function () { let resData; if (xhr.getResponseHeader("content-type").includes("xml")) { resData = xhr.responseXML; } else { resData = JSON.parse(xhr.responseText); } options.success(resData); } if (options.method == "get") { xhr.send(); } else { xhr.send(sendData); } } function o2u(obj) { let keys = Object.keys(obj); let values = Object.values(obj); return keys.map((v, k) => { return `${v}=${values[k]}`; }).join("&"); }
- 請求百度接口
```js
https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=hello&cb=succFn
```
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="jsonp.js"></script> <title>Document</title> </head> <body> <h1>百度搜索</h1> <input type="text" class="myinput" /> <div class="exchange"></div> </body> <script> // console.log(ajax); document.querySelector(".myinput").onblur = function(){ ajax({ url:"https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su", dataType:"jsonp", data:{ wd:this.value }, success:function(res){ let data = res.s; let html = "<ul>"; data.forEach(v=>{ html += "<li>"+v+"</li>"; }) html += "</ul>"; document.querySelector(".exchange").innerHTML = html; } }) } </script> </html>