示例1:Ajax跨域POST/GET傳輸數據是一個令人糾結的問題
上次合肥網遇到一個專題九涉及到了ajax跨域問題,本身來說,基於安全考慮防止進行跨域調用是沒錯的
但是技術的這東最不好說了,哎,,,還是想辦法突破吧,
最簡單的方法不外乎框架,方法也很多,下面使用jquery的JSONP來做:
jQuery中常用getJSON來調用並獲取遠程的JSON字符串,將其轉換為JSON對象,如果成功,則執行回調函數。原型如下:
jQuery.getJSON( url, [data], [callback] ) 跨域加載JSON數據。
url: 發送請求的地址
url: 發送請求的地址
data : (可選) 待發送key/value參數
callback: (可選) 載入成功時的回調函數
主要用於客戶端獲取服務器JSON數據。
示例2:
后端:
<?php
$json_str = json_encode(array("ddd"=>"11111111"));
echo $_GET['ja'].'('.$json_str.')';
?>
$json_str = json_encode(array("ddd"=>"11111111"));
echo $_GET['ja'].'('.$json_str.')';
?>
前端:
$.getJSON('http://www.liushan.cn/test.php?ja=?',function (json){
alert(json);
});
alert(json);
});
示例2:
服務器腳本,返回JSON數據:
$.getJSON.php
$arr=array("name"=>"zhangsan", "age"=>20);
$jarr=json_encode($arr);
echo $jarr;
$jarr=json_encode($arr);
echo $jarr;
注意兩點:
第一:在返回客戶端之前,先用PHP函數json_encode將要返回的數據進行編碼。
第二:返回到客戶端用的是echo,而不是return。
下面是核心的客戶端代碼:
$.getJSON.html
<script language="javascript" type="text/javascript" src="./js/jquery.js"></script>
<script language="javascript" type="text/javascript">
function getjs()
{
$.getJSON("$.getJSON.php", {}, function(response){
alert(response.age);
});
}
<script language="javascript" type="text/javascript">
function getjs()
{
$.getJSON("$.getJSON.php", {}, function(response){
alert(response.age);
});
}
<input type="button" name="btn" id="btn" value="test" onClick="javascript:getjs();"/>
注意一點:
由於在PHP中是用JSON編碼返回值,所以此處必須用getJSON去調用PHP文件,從而獲取數據。同時可以注意到,經由getJSON得到的數據已經變成了一個對象數組,可以用response.name,response.age很直觀的獲取返回值。
當然強大jquery還有另外一個getScript
看他的演示示例:
jQuery.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){
$("#go").click(function(){
$(".block").animate( { backgroundColor: 'pink' }, 1000)
.animate( { backgroundColor: 'blue' }, 1000);
});
});
$("#go").click(function(){
$(".block").animate( { backgroundColor: 'pink' }, 1000)
.animate( { backgroundColor: 'blue' }, 1000);
});
});
案例:
- <script>
- $(document).ready(function(){
- $.ajax({
- url:'http://localhost/test/jsonp.php',
- dataType:"jsonp",
- jsonp:"jsonpcallback",
- timeout: 5000,
- success:function(data, status){
- alert('success: ' + status);
- var $ul = $("<ul></ul>");
- $.each(data,function(i,v){
- $("<li/>").text(v["id"] + " " + v["name"]).appendTo($ul)
- });
- $("#res").append($ul);
- },
- error:function(XHR, textStatus, errorThrown){
- alert('error: ' + textStatus);
- alert('error: ' + errorThrown);
- }
- });
- });
- lt;/script>
- $jsonp = $_GET['jsonpcallback'];
- $arr = array(
- 'id' => '1',
- 'name' => 'test'
- );
- echo $jsonp, '([', json_encode($arr), '])';
- ?>
