微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jsonp和CORS跨域实现

一、jsonp,使用jquery封装的$.ajax,返回数据类型要设置为jsonp

示例:

$.ajax({
    type: 'get',
    contentType: "application/json; charset=utf-8",
    url: "http://localhost:8080/aqi/getCityList.PHP",
    dataType: 'jsonp',    < /span>
jsonp: "callback",/ / 传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(认为: callback)
    jsonpCallback: "success_jsonpCallback", //自定义的jsonp回调函数名称认为jQuery自动生成随机函数名
    success: function(json) {
        getCityListSuccess(json);
    },
    error: function(data, textStatus, errorThrown) {
        console.log("error" + ' ' + JSON.stringify(data) + textStatus + errorThrown);
    }
});或者使用
$.getJson, 在调用的url添加 & callback = ? $.getJSON("http://localhost:8080/aqi/getDetailsByTimepointAndCityId.PHP?callback=?", {    "time_point": time_point,    "city_id": city_id
}, function(json) {
    $('#radar-dialog').css("display", "block");
    $('#radar-dialog').dialog({
        title: radar_cityname + "市," + timepoint,
        width: 350,
    });
    formaTradarData(json);
});

PHP端的代码为:

<?PHPheader("Content-Type: text/html;charset=utf-8");  $db_name="aqidata.db";$conn = new sqlite3($db_name);$callback = $_GET['callback'];$resultarray=array();  $sql = "select * from 'city' where 1=1 order by id";  $result = $conn->query($sql);  $i=0;  while ($row = $result->fetchArray(sqlite3_ASSOC)) {    $resultarray[$i]=$row;$i++;
  }echo $callback.'('.json_encode($resultarray).')';?>

注意:1、ajax中要指定jsonp参数,然后后端要把回调函数名称写入到返回值中。

我参考的博文是:http://www.cnblogs.com/xcxc/p/3729660.html

二、用CORS(Cross-Origin Resource Sharing),这个官方草案。

就是在后端代码PHP)加入:

header("Access-Control-Allow-Origin:*");

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐