加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

jsonp和CORS跨域实现

发布时间:2020-12-16 19:09:48 所属栏目:百科 来源:网络整理
导读:写js时总是会遇到跨域请求的问题,现在了解了两种方法,记录之: 1)jsonp,使用jquery封装的$.ajax,返回数据类型要设置为jsonp,示例: $.ajax({ type: 'get',contentType: "application/json; charset=utf-8",url: "http://localhost:8080/aqi/getCityLis

写js时总是会遇到跨域请求的问题,现在了解了两种方法,记录之:

1)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自动生成的随机函数名</span>
        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端的代码为:

<?php
   header("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


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

就是在后端代码(php)加入:
header("Access-Control-Allow-Origin:*");

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读