$.ajax和$.getJson解决跨域请求

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

1)使用$.ajax,但是返回数据类型要设置为jsonp,示例:

     $.ajax({
        type: 'get',
        contentType: "application/json; charset=utf-8",
        url: "http://localhost:8080/aqi/getCityList.php",
        dataType: 'jsonp',
        headers: {
            Accept: "application/json",
            "Access-Control-Allow-Origin": "*"
        },
        crossDomain: true,
        async: false,
        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);
        }
    });

PHP端的代码为:

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

	echo $callback.'('.json_encode($resultarray).')';

?>

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

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

2)用$.getJSON,这个函数就支持跨域调用。

     $.getJSON("http://localhost:8080/aqi/getCityList.php",function(json){
      getCityListSuccess(json);
     });

但是后端代码(php)要加入:

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

不然会报错:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. 

我参考的博文是:http://blog.163.com/[email protected]/blog/static/164637467201442253942499/?latestBlog

时间: 2024-10-30 06:43:49