技术文档

nodejs+jsonp

2017-03-22  本文已影响54人  last_edc

服务端

app.js

var express = require('express');
var app = express();

app.get('/',function(req,res){
    console.log('index')
    res.send({name:'John',age:18});
})
app.get('/callback=:cbk',function(req,res){
    var bk = req.params.cbk
    var vt = {name:'Tim',age:28,id:bk};
    res.send(bk+'('+JSON.stringify(vt)+')');
})
app.listen(3000);

客户端

test.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>test</title>
    </head>
    <script  src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <body>

    </body>
    <script type="text/javascript">
// 1.用jQuery
        $.getJSON('http://104.160.33.74:3000/callback=?',function(data){
            var dt = JSON.parse(data);
            console.log(data);
            console.log(data.name);
        });
// 2.原生
        function addScript(url){
            var scpt = document.createElement('script');
            scpt.src = url;
            document.body.appendChild(scpt);
        }
        function person(dt){
            document.open();
            document.write(dt.name)
            document.close();
            console.log(dt)
        }

        window.onload=function(){
            addScript('http://104.160.33.74:3000/callback=person')
        }
    </script>
</html>
上一篇下一篇

猜你喜欢

热点阅读