• [js]ajax-异源请求jsonp


    参考:
    http://www.cnblogs.com/whatisfantasy/p/6237713.html
    http://www.cnblogs.com/freely/p/6690804.html
    http://www.cnblogs.com/LetMe/articles/7616267.html

    ajax请求-解放每次手动输url

    js的XMLHttpRequest对象

    我们使用XMLHttpRequest对象来发送一个Ajax请求

    用xhr发一个ajax请求

    因为我是webstorm,因此自带音响哈.

    也就是这个接口 http://localhost:63343/web_learn/ajax/ajax/data.txt 可以被访问到,这里我们不手动访问呢了,用ajax来访问.

    这里我们用ajax来请求这个接口,并将内容打印到console口

    <script>
        var xhr = new XMLHttpRequest(); //1.创建xhr对象
        xhr.open('get', 'http://localhost:63343/web_learn/ajax/ajax/data.txt', true); //2.准备发起url,默认异步true
    
        xhr.onreadystatechange = function () { //3.回来的数据该怎么处理?
            if (xhr.readyState === 4 && xhr.status === 200) {
                console.log(xhr.responseText);
            }
        };
        xhr.send(null); //4.开始发射
    </script>
    

    同源访问-简写url

    <script>
        var xhr = new XMLHttpRequest();
        xhr.open('get', 'data.txt', true);//这里url可以简写哦,默认代表访问源
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                console.log(xhr.responseText);
            }
        };
        xhr.send(null);
    </script>
    

    异源访问

    这里我们访问 http://www.weather.com.cn/data/sk/101010100.html 这个接口

    <script>
        xhr = new XMLHttpRequest();
        xhr.open('get', 'http://www.weather.com.cn/data/sk/101010100.html', true); //跨站访问不允许Access-Control-Allow-Origin' header
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200){
                console.log(xhr.responseText);
            }
        };
        xhr.send(null);
    </script>
    

    ajax跨源访问是不允许的, 浏览器不允许他这样搞. 也是为了安全的缘故吧.

    解决ajax异源请求

    浏览器不允许ajax来跨源,但是运行link script img等标签跨源.

    借助script标签来解决异源问题.

    我们找了个接口

    https://suggest.taobao.com/sug?code=utf-8&q=%E5%9B%B4%E5%B7%BE&callback=fn
    

    发现clallback=xx 他返回你传递给他的, 可见后端获取到了这个参数(query),然后作为一部分返回给前端

    jsonp.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>jsonp</title>
    </head>
    <body>
    <script>
        //jsonp方式解决异源问题
        function fn(data) {
            console.log(data);
        }
    </script>
    <script type="text/javascript"
            src="https://suggest.taobao.com/sug?code=utf-8&q=%E5%9B%B4%E5%B7%BE&callback=fn"> //这里fn其实是函数名, 返回结果fn(一坨data), 恰好触发了页面的fn函数
    </script>
    </body>
    </html>
    

    /getdata?callback=fn部分自己实现--nodejs实现这个接口

    参考: nodejs初探http/url/fs模块

    即实现传什么函数名,返回什么

    如传fn返回fn(data), 传func,返回func(data)

    app.js 我们设置函数名为maotai,返回maotai(data)

    var http = require('http'), //导入http url fs模块
        url = require('url'),
        fs = require('fs');
    
    
    s1 = http.createServer(function (req, res) {// 创建服务器
        var urlObj = url.parse(req.url, true),  // 接受req对象
            pathname = urlObj['pathname'],      // 取出req里的pathname
            query = urlObj['query']; //获取参数 /getall?cb=maotai" 里的cb
    
        // 不同的.html .css 返回时候设置http head不同的mime类型
        var reg = /.(HTML|CSS|JS|JSON|TXT|ICO)/i; //正则判断mime类型
        if (reg.test(pathname)) {
            var suffix = reg.exec(pathname)[1].toUpperCase();//mime统一大写比对
            var suffixMIME = null;
            switch (suffix) {
                case "HTML":
                    suffixMIME = 'text/html';
                    break;
                case "JS":
                    suffixMIME = 'text/javascript';
                    break;
                case "CSS":
                    suffixMIME = 'text/css';
                    break;
                case "JSON":
                    suffixMIME = 'application/json';
                    break;
                case "ICO":
                    suffixMIME = 'application/octet-stream';
                    break;
            }
    
    
            try {
                con = fs.readFileSync('.' + pathname);
                res.writeHead(200, {'content-type': suffixMIME + ';charset=utf-8'});
                res.end(con);
            } catch (e) {
                res.writeHead(404, {'content-type': 'text/plain;charset=utf-8'});
                res.end("file not found")
            }
        }
    
        if (pathname === "/getall") {
            var fnName = query["cb"]; //获取cb=maotai
            con = fs.readFileSync('./data.txt', 'utf-8');
            con = 'a,b';
            res.writeHead(200, {'content-type': 'application/json;charset=utf-8'});
            res.end(fnName + '(' + con + ',22)'); // end即返回 maotai(a,b,22)
        }
    });
    
    s1.listen(1234, function () {
        console.log("http://127.0.0.1:1234/getall?cb=maotai");
    });
    
    

    启动nodejs服务端

    实现这个接口

    http://127.0.0.1:1234/getall?cb=maotai
    

    返回结果

    触发页面

    <script>
        var a = 12;
        var b = 13;
        function maotai(a,b,num) {
            console.log(a,b,num);
        }
    </script>
    
    <!--//jsonp可以返回任意格式字符串,但一般返回的是json格式字符串-->
    <script type="text/javascript" src="http://127.0.0.1:1234/getall?cb=maotai"></script>
    

    访问返会结果.

  • 相关阅读:
    日♂常
    日♂常
    生哥的hu测
    生哥的hu测
    118.编程实现添加环境变量
    4.泡妞与设计模式(五) 原型模式
    4.泡妞与设计模式(四)享元模式
    2.泡妞与设计模式(三) 外观模式
    1.泡妞与设计模式(二)合成模式
    0.泡妞与设计模式(一)工厂模式
  • 原文地址:https://www.cnblogs.com/iiiiiher/p/8406314.html
Copyright © 2020-2023  润新知