zoukankan      html  css  js  c++  java
  • jsonp


    <!DOCTYPE html>
    <html>

        <head>
            <meta charset="utf-8" />
            <title></title>
            <script>
                
                //JSONP:域(协议、域名、端口号)有一个不同就不同。所以不能直接跨域访问别的服务器上的数据
                //JSONP是跨域手段之一
                
                //JSONP(JSON with padding)是被包含在函数调用中的JSON. success('{"name":"zhangsan"}')
                //jsonp的原理,是利用外链外域的js的时候,能够不出错,从而实现跨域访问的
                //解决办法是创建一个script标签,然后把网址作为src的属性值赋值
                
                //解决数据的问题,写一个回调函数,将数据作为参数传进去
                //然后网址写成带参数的方式
                
                //这里为了测试,手动修改weather.js文件,用函数名加上括号把原来weather.js文件
                //包起来,这就是JSONP(被包含在函数调用中的JSON),这样子就能得到数据了
                
                //注意,实际工作中,不需要我们手动修改weather.js文件,我们只需要将网址改成原来网址加上
                //?callback=success就可以,后端工程师会处理好,将数据改成是
                //success('{"city":'SH',"mintemp":-1,"maxtemp":3,"wind":3, "pm2_5": 50}')
                //形式的。
                
                function jsonp(){
                    var _script = document.createElement("script");
                    //为了取得服务器的数据,给url加上参数?callback=success(callback=加上函数名)
                    _script.src = "http://localhost/AJAX/weather.js?callback=success";
                    document.body.appendChild(_script);
                }
                
                //reponse是服务器传回来的数据,reponse就是json字符串
                function success(response){
                    var obj = eval("("+response+")"); //用eval方法转换成json对象
                    //console.log(obj);
                     // alert("城市"+obj.city+"最低温度"+obj.mintemp);
                     var oDiv1 = document.getElementById("div1");
                     oDiv1.innerHTML = "城市 "+obj.city+" 最低温度 "+obj.mintemp;
                     //这里获取到了数据,进一步操作数据做的事,可以写在这个函数里。
                }
                    
                
            </script>
            
        </head>

        <body>
            <div id="div1"></div>
            这是第一个网页,测试JSONP
            <button onclick="jsonp()">这是一个跨域请求,请求天气预报的数据</button>
        </body>

    </html>

  • 相关阅读:
    2013.4.15 Particle Swarm Optimization with Skyline Operator for Fast Cloudbased Web Service Composition
    Adaptive service composition in flexible processes
    2013.4.13 DomainSpecific Service Selection for Composite Services
    2013.4.14 Modeling and Algorithms for QoSAware Service Composition in VirtualizationBased Cloud Computing
    2013.5.29 Towards Networkaware Service Composition in the Cloud
    Efficient algorithms for Web services selection with endtoend QoS constraints
    SQL Server中常用的SQL语句
    接口限流自定义注解
    linux服务器生产环境搭建
    MVEL自定义函数重复掉用报错:duplicate function
  • 原文地址:https://www.cnblogs.com/yuejie/p/5986326.html
Copyright © 2011-2022 走看看