jquery處理json對象_jquery

來源:互聯網
上載者:User

在伺服器端的php指令碼:

複製代碼 代碼如下:

<?php  
$data['id'] = 1;  
$dat['name'] = "mary";  
$da['red']= array_merge($data,$dat);  
 
$data1['id'] = 2;  
$dat1['name'] = "燕子";  
$da['blue']= array_merge($data1,$dat1);  
print_r($da);   //列印出來是一個二維數組(如下)  
/*
Array 
( 
    [red] => Array 
        ( 
            [id] => 1 
            [name] => mary 
        ) 
 
    [blue] => Array 
        ( 
            [id] => 2 
            [name] => 燕子 
        ) 
) 
*/ 
 
 
echo json_encode($da);//輸出的是一個轉化成json格式的字串,可以直接在js中用(如下)  
/*
{"red":{"id":1,"name":"mary"},"blue":{"id":2,"name":"\u71d5\u5b50"}} 
*/ 
?> 

jquery指令碼:
返回到js後的處理:
第一種要用到varl轉化的:是字串的時候就要用eval轉化成jquery對象(如下)

複製代碼 代碼如下:

var arr = '{"red":{"id":1,"name":"mary"},"blue":{"id":2,"name":"\u71d5\u5b50"}}';   //\u71d5\u5b50這個是php中自動轉換的  
var dataObj = eval("("+arr+")");    //這裡要加上加好括弧和雙引號的原因我也不知道,就當是json文法,只能死記硬背了  
    $.each(dataObj,function(idx,item){  
    //輸出    
    alert(item.id+"哈哈"+item.name);  
}) 

第二種:不需要轉化的:

複製代碼 代碼如下:

var arr = {"red":{"id":1,"name":"mary"},"blue":{"id":2,"name":"\u71d5\u5b50"}};  
$.each(arr,function(idx,item){  
    //輸出  
    alert(item.id+"哈哈"+item.name);  
}) 

迴圈也有兩種方法:

複製代碼 代碼如下:

//方法一:

$.each(arr,function(idx,item){       
    //輸出  
    alert(item.id+"哈哈"+item.name);  
}) 
//方法二:

for(var key in arr){  
    alert(key);  
    alert(arr[key].status);  
} 

聯繫我們

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