jsonp跨域訪問資料

來源:互聯網
上載者:User

標籤:

執行個體一,使用 jquery 的 $.getJSON 方法

 

//前端js :

$("#selId").click(function() {
$.getJSON("http://www.example.com/remote.php?callback=?", // callback=?參數是重點,會傳遞到後台自動處理
{name: ‘max‘, age: 23, str: ‘hello‘},
function(data) {
console.log(data);
}
);

});

//後端remote.php

$callback = $_REQUEST[‘callback‘]; //前台傳遞過來的 ? 號,被jquery自動解析為一個函數名
$arr = array(‘name‘=>‘hello‘, ‘age‘=>23, ‘male‘=>‘female‘, ‘str‘=>$_REQUEST[‘str‘]);
$tmp = json_encode($arr);
echo $callback."($tmp)"; //實質上,後台這裡只需要返回 “funName({ name: ‘max‘, age: 23 } json資料 )”格式的字串就行了

 

 

執行個體二,使用 jquery 的 $.ajax 方法

//前端代碼:

$("#selId").click(function() {
$.ajax({
type: "GET",

//asyn 預設為 true,表示使用非同步請求;false 表示使用同步請求,同步請求將鎖定瀏覽器,使用者其他動作需等待請求完成才可以執行
async: false,
url: "http://www.example.com/remote.php", // 跨域的後台檔案,主要是產生字串;
dataType: "jsonp", //使用 jsonp 方式擷取
jsonp: "callback", //用於獲得jsonp回呼函數名的參數名,一般為 callback 

/**自訂的 jsonp 回呼函數名,此時後台返回字串為 echo“remoteHandler( json )”; 用 ? 的話jquery會隨機自動產生,後台代碼則為 $callback=$_REQUEST[‘callback‘], echo $callback. jsonStr.

*/
jsonpCallback: "remoteHandler",
success: function(json) {
console.log(json);
},

});

});

 

 

//後台remote.php

$arr = array(‘name‘=>‘hello‘, ‘age‘=>23, ‘male‘=>‘female‘, ‘str‘=>$_REQUEST[‘str‘]);

$tmp = json_encode($arr);
echo "remoteHandler($tmp)"; // remoteHandler 與前台傳進來的 jsonpCallback: "remoteHandler" 對應

jsonp跨域訪問資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.