PHP中AJAX和JSONP實現跨域請求

來源:互聯網
上載者:User
在之前我寫過“php返回json資料簡單一實例”,“php返回json資料中文顯示的問題”和“在PHP語言中使用JSON和將json還原成數組”。希望能協助到大家。

執行個體1

test.html

<!doctype html><html><head><meta charset="utf-8"><title>test</title><script src="jquery-1.5.2.min.js"></script><script src="ajax.js"></script></head> <body></body></html>

ajax.js

$.ajax({    type : "post",    url : "ajax.php",    dataType : "jsonp",    jsonp: "callback",//傳遞給請求處理常式或頁面的,用以獲得jsonp回呼函數名的參數名(預設為:callback)    jsonpCallback:"success_jsonpCallback",//自訂的jsonp回呼函數名稱,預設為jQuery自動產生的隨機函數名    success : function(json){        alert('success');    },    error:function(){        alert('fail');    }});

ajax.php

<?php $data = ".......";$callback = $_GET['callback'];echo $callback.'('.json_encode($data).')';exit; ?>

jquery-1.5.2.min.js

自己上網下載

當使用jsonp時,使用 JSONP 形式調用函數時,如 "myurl?callback=?" jQuery 將自動替換 ? 為正確的函數名,以執行回呼函數。

執行個體2

test.html

<!doctype html><html><head><meta charset="utf-8"><title>test</title><script src="jquery-1.5.2.min.js"></script><script src="ajax.js"></script></head> <body><form name="form"><input type="text" name="sex"><input type="text" name="age"><input type="button" id="btn" value="button" /></form></body></html>

ajax.js

$(document).ready(function(){     $("#btn").click(function(k) {        //...        var j = $("form").serializeArray();//序列化name/value        $.ajax({            type: 'GET',  //這裡用GET            url: 'ajax.php',            dataType: 'jsonp',  //類型            data: j,            jsonp: 'callback', //jsonp回調參數,必需            async: false,            success: function(result) {//返回的json資料                alert(result.message); //回調輸出                                 result = result || {};                if (result.msg=='err'){                    alert(result.info);                }else if (result.msg=="ok"){                    alert('提交成功');                }else{                    alert('提交失敗');                }                             },            timeout: 3000        })        //...    });     });

ajax.php

<?php$callback = isset($_GET['callback']) ? trim($_GET['callback']) : ''; //jsonp回調參數,必需$date = array("age"=>$_GET['age'], "message"=>$_GET['age']);$date["msg"]="err";$date["info"]="因人品問題,發送失敗";$tmp= json_encode($date); //json 資料echo $callback . '(' . $tmp .')';  //返回格式,必需?>

jquery-1.5.2.min.js

自己從網上下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.