zoukankan      html  css  js  c++  java
  • php+ajax+jquery实现jsonp跨域

    我们有这么个html文件test.html:

    代码如下:


    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
    <title>Untitled Page</title>
    <script type="text/javascript" src="jquery-1.7.2.min.js"></script>
    <script type="text/javascript">
    jQuery(document).ready(function(){
    $.ajax({
    type: "GET",
    async: false,
    url:"test.php",
    dataType: "jsonp",
    jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
    jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
    success: function(json){
    alert('您查询到航班信息:票价: ' + json.price + ' 元,余票: ' + json.tickets + ' 张。回调函数名为: '+json.func);
    },
    error: function(){
    alert("fail");
    }
    });
    });
    </script>
    </head>
    <body>
    </body>
    </html>

    然后,你可以再找个另外一个域名的web目录,将文件test.php:


    <?php
    $callback = $_GET["callback"];
    $a = array(
    'code'=>'CA1998',
    'price'=>'6000',
    'tickets'=>20,
    'func'=>$callback,
    );
    $result = json_encode($a);
    echo "flightHandler($result)";
    exit;

    放到这个目录下面去。这样就可以测试了。
    直接在浏览器访问test.html.就可以看到效果了。

  • 相关阅读:
    数据表管理admin
    HDU 5057
    HDU 5056
    HDU 6035(树形dp)
    CodeForces 586D
    Codeforces 940D
    CodeForces 820C
    TOJ4114(活用树状数组)
    2017CCPC中南地区赛 H题(最长路)
    CodeForces 544C (Writing Code)(dp,完全背包)
  • 原文地址:https://www.cnblogs.com/matengfei123/p/6740880.html
Copyright © 2011-2022 走看看