jQuery.getJSON詳解與getJSON和asp.net執行個體(1/3)

來源:互聯網
上載者:User

jquery.getjson詳解與getjson和asp教程.net執行個體
jquery.getjson( url, [data], [callback] ) 跨域載入json資料。
url: 發送請求的地址
data : (可選) 待發送key/value參數
callback: (可選) 載入成功時的回呼函數
主要用於用戶端擷取伺服器json資料。簡單樣本:
伺服器指令碼,返回json資料:
$.getjson.php教程
$arr=array("name"=>"zhangsan", "age"=>20);
$jarr=json_encode($arr);
echo $jarr;
注意兩點:
第一:在返回用戶端之前,先用php函數json_encode將要返回的資料進行編碼。
第二:返回到用戶端用的是echo,而不是return。
下面是核心的用戶端代碼:

$.getjson.html
 代碼如下:
<script language="網頁特效" type="text/javascript" src="./js/jquery.js"></script>
<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();"/>

下面看與asp.net教程 中getjson的應用

準備工作
·customer類

 代碼如下:

public class customer
{
public int unid { get; set; }
public string customername { get; set; }
public string memo { get; set; }
public string other { get; set; }
}


(一)ashx

 代碼如下:

customer customer = new customer
{ unid=1,customername="宋江",memo="天魁星",other="黑三郎"};
string strjson = newtonsoft.json.jsonconvert.serializeobject(customer);
context.response.write(strjson);

 代碼如下:

function getcustomer_ashx() {
$.getjson(
"webdata/json_1.ashx",
function(data) {
var tt = "";
$.each(data, function(k, v) {
tt += k + ":" + v + "<br/>";
})
$("#divmessage").html(tt);
});
}

·通過getjson向ashx請求資料。返回的資料為json對象。
(二)ashx檔案,但返回的是實體集合
 代碼如下:

customer customer = new customer
{ unid=1,customername="宋江",memo="天魁星",other="黑三郎"};
customer customer2 = new customer
{ unid = 2, customername = "吳用", memo = "天機星", other = "智多星" };
list<customer> _list = new list<customer>();
_list.add(customer);
_list.add(customer2);
string strjson = newtonsoft.json.jsonconvert.serializeobject(_list);
context.response.write(strjson);

 

 代碼如下:

function getcustomerlist() {
$.getjson(
"webdata/json_1.ashx",
function(data) {
var tt = "";
$.each(data, function(k, v) {
$.each(v,function(kk, vv) {
tt += kk + ":" + vv + "<br/>";
});
});
$("#divmessage").html(tt);
});
}

首頁 1 2 3 末頁

聯繫我們

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