nodejs+jsonp

作者: last_edc | 来源:发表于2017-03-22 20:13 被阅读54次

    服务端

    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>
    

    相关文章

      网友评论

        本文标题:nodejs+jsonp

        本文链接:https://www.haomeiwen.com/subject/aekanttx.html