码迷,mamicode.com
首页 > Web开发 > 详细

JSONP

时间:2018-01-17 10:08:23      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:lan   gif   log   name   ext   local   pos   test   pen   

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <button id="btn1">请求</button>
    <!-- <script>
    function test(data) {
        alert(data.name);
    }
    </script>
    <script src="http://127.0.0.1:8080/jsonp?callback=test"></script> -->
    <script>
    function addScriptTag(src) {
        var script = document.createElement("script");
        script.setAttribute(‘type‘, ‘text/javascript‘);
        script.src = src;
        document.body.appendChild(script);
    }
    var oBtn = document.querySelector("#btn1");
    oBtn.onclick = function() {
        addScriptTag("http://127.0.0.1:8080/jsonp?callback=hello")
    };
    function hello(data) {
        console.log(data);
    }
    </script>
</body>
</html>

server.js

var http = require(‘http‘);
var url = require(‘url‘);

var querystring = require(‘querystring‘);

var server = http.createServer();

server.on(‘request‘, function (req, res) {
    var urlPath = url.parse(req.url).pathname;
    var qs = querystring.parse(req.url.split(‘?‘)[1]);
    // http://localhost:8080/jsonp?callback=test // { callback: ‘test‘ }
    if (urlPath === "/jsonp" && qs.callback) {
        res.writeHead(200, {
            ‘Content-Type‘: ‘text/plain;charset=utf-8‘
        });
        var data = {
            "name": "Monkey"
        };
        data = JSON.stringify(data);

        var callback = qs.callback + ‘(‘ + data + ‘);‘;

        res.end(callback);
    } else {
        res.writeHead(200, {
            ‘Content-Type‘: ‘text/html;charset=utf-8‘
        });
        res.end(‘Hello World\n‘);
    }
});

server.listen(‘8080‘);

  

JSONP

标签:lan   gif   log   name   ext   local   pos   test   pen   

原文地址:https://www.cnblogs.com/jiujiaoyangkang/p/8301124.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!