jsonp和CORS跨域实现
生活随笔
收集整理的這篇文章主要介紹了
jsonp和CORS跨域实现
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、jsonp,使用jquery封裝的$.ajax,返回數(shù)據(jù)類型要設(shè)置為jsonp
示例:
$.ajax({type: 'get',contentType: "application/json; charset=utf-8",url: "http://localhost:8080/aqi/getCityList.php",dataType: 'jsonp',< /span> jsonp: "callback",/ / 傳遞給請求處理程序或頁面的,用以獲得jsonp回調(diào)函數(shù)名的參數(shù)名(默認(rèn)為: callback)jsonpCallback: "success_jsonpCallback", //自定義的jsonp回調(diào)函數(shù)名稱,默認(rèn)為jQuery自動生成的隨機函數(shù)名</span>success: function(json) {getCityListSuccess(json);},error: function(data, textStatus, errorThrown) {console.log("error" + ' ' + JSON.stringify(data) + textStatus + errorThrown);} });或者使用 $.getJson, 在調(diào)用的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端的代碼為:
<?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參數(shù),然后后端要把回調(diào)函數(shù)名稱寫入到返回值中。
我參考的博文是:http://www.cnblogs.com/xcxc/p/3729660.html
二、用CORS(Cross-Origin Resource Sharing),這個官方草案。
就是在后端代碼(php)加入:
header("Access-Control-Allow-Origin:*");轉(zhuǎn)載于:https://www.cnblogs.com/ziyoublog/p/10774505.html
總結(jié)
以上是生活随笔為你收集整理的jsonp和CORS跨域实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《巨人的花园》课文原文
- 下一篇: 关闭8080端口