写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 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:*");原文链接:https://www.f2er.com/json/289884.html