JSONP

作者: 庄海鑫 | 来源:发表于2018-05-22 21:27 被阅读0次

数据库是什么鬼

  1. 文件系统是一种数据库
  2. MySQL 是一种数据库
    只要能长久地存数据,就是数据库

发送请求的几种方式

1.form
2.a
3.img
4.link
5.script
...

用数据库做加法

举一个用户付款的例子
1.不用数据库
2.使用文件系统
3.使用文件系统时,使用iframe显示是否当前页面请求成功
4.,使用img标签发送请求
5使用文件系统时,并用script标签发送请求,然后在服务器端(刷新页面或者修改innerText) SRJ(Server Render Javascript)

6.使用文件系统时,并用script标签发送请求,比如说是frank写的前端页面向jack写的后台发送请求),然后在服务器端(刷新页面或者修改innerText) SRJ(Server Render Javascript)
7.使用jQuery中的jsonp
https://github.com/zhuanghaixin/node_server

什么是JSONP(面试)?

原生JS:
前端

 button.addEventListener('click',(e)=>{
        let script=document.createElement('script');
        let functionName='zhx'+parseInt(Math.random()*10000,10);
        window[functionName]=function(result){
            alert('这是frank写的前端代码');
            alert(`我得到的结果是${result}`);
            if(result==='success'){
                amount.innerText=amount.innerText-1;
            }else{
              alert('fail');
            }
        }
   
         script.src=`http:jack.com:8002/pay?callback=${functionName}`;
        document.body.appendChild(script);
        script.onload=function (e) {
           // alert('success');// 先返回响应结果,再返回加载结果
            // window.location.reload();  //刷新当前页面
            // amount.innerText=amount.innerText-1;
            // debugger;
            e.currentTarget.remove();  //生成的script标签立即移除
            delete window[functionName]; //删除生成的函数名functionName
        }
        script.onerror=function(){
            alert('fail')
            e.currentTarget.remove();  //生成的script标签立即移除
            delete window[functionName]; //删除生成的函数名functionName
        }
    })

后端

// 这是jack.com的后台代码
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if (!port) {
    console.log('请指定端口号好不啦?\nnode server.js 8888 这样不会吗?')
    process.exit(1)
}

var server = http.createServer(function (request, response) {
    var parsedUrl = url.parse(request.url, true)
    var path = request.url
    var query = ''
    if (path.indexOf('?') >= 0) {
        query = path.substring(path.indexOf('?'))
    }
    var pathNoQuery = parsedUrl.pathname
    var queryObject = parsedUrl.query
    var method = request.method

    /******** 从这里开始看,上面不要看 ************/

    console.log('方方说:得到 HTTP 路径为\n' + path)
    console.log('方方说:查询字符串为\n' + query)
    console.log('方方说:不含查询字符串的路径为\n' + pathNoQuery)
    if (path == '/') {
        var string = fs.readFileSync('./index1_4.html','utf8');
        var amount=fs.readFileSync('./db','utf8'); //100
        string=string.replace('&&&amount&&&',amount);
        response.setHeader('Content-Type', 'text/html; charset=utf-8')
        response.write(string);
        response.end()
    }else if(pathNoQuery=='/pay'){
        var amount=fs.readFileSync('./db','utf8') //100
        var newAmount=amount-1;
        // console.dir(parsedUrl.query.callbackName);

        if(Math.random()>0.5){
            fs.writeFileSync('./db',newAmount);
            response.setHeader('Content-Type','application/javascript');
            response.statusCode=200;
            response.write(`
  
             ${parsedUrl.query.callback}.call(undefined,'success');
           
            
            `);

        }else{
            // response.statusCode=400;
            response.write('alert("失败")');
        }
        response.end();

    }
    else if (path == '/style1&style2.css') {
        response.setHeader('Content-Type', 'text/css; charset=utf-8')
        response.write('body{background-color: #ddd;}h1{color: red;}')
        response.end()
    } else if (path == '/main.js') {
        response.setHeader('Content-Type', 'text/javascript; charset=utf-8')
        response.write('alert("这是JS执行的")')
        response.end()
    } else {
        response.statusCode = 404
        response.end()
    }


    /******** 代码结束,下面不要看 ************/
})

server.listen(port)
console.log('监听 ' + port + ' 成功\n请用在空中转体720度然后用电饭煲打开 http://localhost:' + port)

请求方:frank.com的前端程序员(浏览器)
响应方:jack.com的后端程序与(后端)
1.请求方动态创建一个script的标签,它的src指向响应方(服务器的ip地址),同时传一个查询参数(?callback=functionName)
2.响应方(服务器)通过

       ${parsedUrl.query.callback}.call(undefined,'你要的数据);

查询参数callback,构造形如

1.xxx.call(undefined,'你要的数据')
2.xxx('你要的数据')

这样的响应
3.浏览器接受响应,就会执行xxx.call(undefined,‘你要的数据’)
4.那么请求方就知道他要的数据了

JSONP 为什么不支持 POST

1.JSONP是通过动态创建script标签实现的
2.动态创建script,只能用GET,不能用POST

jQuery实现jsonp

    $.ajax({
            url: "http://jack.com:8002/pay",

            // The name of the callback parameter, as specified by the YQL service
            jsonp: "callback",

            // Tell jQuery we're expecting JSONP
            dataType: "jsonp",

            // Tell YQL what we want and that we want JSON
             data: {
                  q: "select title,abstract,url from search.news where query=\"cat\"",
                 format: "json"
               },

            // Work with the response
            success: function( response ) {
                console.log( response ); // server response
                if(response==='success'){
                    alert('success');
                            amount.innerText=amount.innerText-1;
                        }else{

                        }
            }
        });

参考资料:javascript之跨域

相关文章

网友评论

    本文标题:JSONP

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