json和jsonp

長空發表於2017-06-07

1. json

json的全名是JavaScript Object Notation(js物件標記),也就是一種資料結構,多用於資料結構描述。

2. jsonp

jsonp的全稱是json with padding(json的襯墊),就是對json資料做一下其他處理。

3. jsonp的由來

ajax不允許跨域請求,但是html有個漏洞就是帶src標籤的東西是可以跨域的,如

<script src=""/>
<img src=""/>

jsonp就是基於這個來實現的跨域請求。

4. jsonp前端原生實現

// index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    
</head>
<body>
    <script type="text/javascript">
        function cb(data) {// 預設回撥函式是cb
            alert(data.name);
        }
    </script>
    <script src="http://127.0.0.1:3000?callback=cb"></script>
</body>
</html>

5. jsonp後端實現

// index.js
var http = require(`http`);

http.createServer((req, res) => {
  res.writeHead(200, {
    `content-type`: `text/json;charset=utf-8`
  });
  var data = {
    "name": "michael"
  };
  data = JSON.stringify(data);
  //假設我們定義的回撥函式名為cb
  var callback = `cb` + `(` + data + `);`;
  res.end(callback);
}).listen(3000);

6. 執行

首先在index.js所在的資料夾下執行

node index.js

然後在index.html所在的資料夾下執行

http-server -p 4000

這樣一個3000埠,一個4000埠,實現了跨域請求。此時開啟index.html,會展示alert(`michael`)

7. 後記

以上只是簡單實現,如果想在專案中大規模使用需要封裝很多東西。如果在開發環境中使用完全可以使用代理伺服器完成,如果真的有跨域的業務,這也是一種解決方案。

相關文章