When writing js, we always encounter the problem of cross-domain requests. Now we know two methods and record them:
1) Use $.ajax, but the return data type should be set to jsonp, example:
$.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).')'; ?>
The blog post I refer to is: http://www.cnblogs.com/xcxc/p/3729660.html
2) Using $.getJSON, this function supports cross-domain calls.
$.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.
The above introduces $.ajax and $.getJson to solve cross-domain requests, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.