寫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"> </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).')'; ?>
我參考的博文是: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教程有興趣的朋友有所幫助。