Jquery handles json objects

  • 2020-03-30 04:15:09
  • OfStack

On the server side of the PHP script:


<?php  
$data['id'] = 1;  
$dat['name'] = "mary";  
$da['red']= array_merge($data,$dat);  
 
$data1['id'] = 2;  
$dat1['name'] = " The swallow ";  
$da['blue']= array_merge($data1,$dat1);  
print_r($da);   //Printed out as a 2-d array (as shown) & NBSP;   < br / > /*
Array 

    [red] => Array 
        ( 
            [id] => 1 
            [name] => mary 
        ) 
 
    [blue] => Array 
        ( 
            [id] => 2 
            [name] => The swallow  
        ) 

*/ 
 
 
echo json_encode($da);//The output is a string converted to json, which you can use directly in js (as shown) & NBSP;   < br / > /*
{"red":{"id":1,"name":"mary"},"blue":{"id":2,"name":"u71d5u5b50"}} 
*/ 
?> 

The jquery script:
Processing after returning to js:
The first thing to do with varl is to convert a string to a jquery object using eval.


var arr = '{"red":{"id":1,"name":"mary"},"blue":{"id":2,"name":"u71d5u5b50"}}';   //u71d5u5b50 this is automatically converted in PHP & PI;   < br / > var dataObj = eval("("+arr+")");    //I don't know why I put the parentheses and double quotation marks there, but it's just json syntax, which I have to memorize & NBSP;;   < br / >     $.each(dataObj,function(idx,item){  
    //The output         < br / >     alert(item.id+" Ha ha "+item.name);  
}) 

Second: those that do not need to be converted:


var arr = {"red":{"id":1,"name":"mary"},"blue":{"id":2,"name":"u71d5u5b50"}};  
$.each(arr,function(idx,item){  
    //The output     < br / >     alert(item.id+" Ha ha "+item.name);  
}) 

There are also two ways to loop:


//Method one: $.each(arr,function(idx,item){       
    //The output     < br / >     alert(item.id+" Ha ha "+item.name);  
}) 
//Method 2: for(var key in arr){  
    alert(key);  
    alert(arr[key].status);  


Related articles: