Ajax

JSONP实现原理-简析

2018-11-29  本文已影响146人  三省吾身_9862

使用script标签是如何实现跨域请求的,它是一个新技术,还是一个技巧?
下面我们来看看,其中简单的原理:

我们写一个很平常的example.js,文件内容展示如下:

getJson({
    results: [
        {
            name: 'xxx',
            code: 1
        }
    ]
});

接下来,再写一个简单的index.html文件:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>jsonp</title>
    <script>
      function getJson(data) {
        console.log(data);
      }
    </script>
    <script src="http://127.0.0.1:3000/example.js"></script>
   </head>
   <body></body>
</html>

上面的index.html代码,当成功的请求到example.js后,相当于这样:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>jsonp</title>
    <script>
      function getJson(data) {
        console.log(data);
      }
    </script>
    <script>
      //  这里是:src="http://127.0.0.1:3000/example.js"请求成功后,返回的代码(数据)
      getJson({
        results: [
          {
            name: 'xxx',
            code: 1
          }
        ]
      });
    </script>
   </head>
   <body></body>
</html>

相信写到这里,是能看得明白的,下面正式开始说JSONP的实现,我用的是nodejs后台:

前端代码index.html,给"http://http://127.0.0.1:3000/example.js"请求地址加一个get请求参数?callback=getJson,代码示例如下:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>jsonp</title>
    <script>
      function getJson(data) {
        console.log(data);
      }
    </script>
    <script src="http://127.0.0.1:3000/example.js?callback=getJson"></script>
   </head>
   <body></body>
</html>

后端server.js代码如下:

const express = require('express');
const server = express();

server.use('/example.js', (req, res) => {
  // req.query.callback是getJson
  let methodName = req.query.callback; 
  let data = {
     results: [
       {
         name: 'xxx',
         code: 1
       }
     ]
   };
  let dataStr = JSON.stringify(data),
      // 相当于sendStr = `getJson(${dataStr})`
      sendStr = `${methodName}(${dataStr})`;
  res.send(sendStr);
});

server.listen(3000);
console.log('server running at 127.0.0.1:3000');

当<script src="http://127.0.0.1:3000/example.js?callback=getJson"></script>请求成功后,index.html代码解析如下:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>jsonp</title>
    <script>
      function getJson(data) {
        console.log(data);
      }
    </script>
    <script>
      // 这里是:src="http://127.0.0.1:3000/example.js?callback=getJson"请求成功后,返回的代码(数据)
      getJson('{"results":[{"name":"xxx","code":1}]}')
    </script>
   </head>
   <body></body>
</html>

最后声明,为了方便大家理解,我把请求写成了一个example.js,其实接口只要一个字符串就可以了,例如"http://127.0.0.1:3000/example?callback=getJson",其中.js文件格式,完全是为了帮助大家理解。

上一篇下一篇

猜你喜欢

热点阅读