写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 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"> $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).')'; ?>
我参考的博文是:http://www.cnblogs.com/xcxc/p/3729660.html
2)用$.getJSON,这个函数就支持跨域调用。
$.getJSON("http://localhost:8080/aqi/getCityList.php",function(json){ getCityListSuccess(json); });
header("Access-Control-Allow-Origin:*");
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
以上就介绍了$.ajax和$.getJson解决跨域请求,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。