2015-11-01 108 views
-3

請問如何用foreach打印數據?用foreach打印JSON數據

我通常使用PHP對於這一點,但這裏的服務器不包括PHP ...

感謝您的幫助。


{ 
    "data": { 
     "items": [ 
      { 
       "id": 1, 
       "status": "active", 
       "price": "300", 
       "size": { 
        "width": 12, 
        "height": 12 
       }, 
       "english": { 
        "name": "My new item", 
        "description": "My item description" 
       } 
      }, 
      { 
       "id": 2, 
       "status": "active", 
       "price": "560", 
       "size": { 
        "width": 11, 
        "height": 14 
       }, 
       "english": { 
        "name": "My new item 2", 
        "description": "My paint item 2" 
       } 
      } 
     ] 
    } 
} 
+2

它已經被解析:d –

+0

如何在foreach我可以打印DATAS好嗎? – Tomas

回答

1

這取決於你的 '解析' 是什麼意思。我建議你考慮一下這個問題,然後看看下面的例子。它使用一個JavaScript庫jQuery,這是非常容易理解和廣泛使用的。

function example() 
{ 
    var response = ""; 
    var form_data = { 
     username: username, 
     password: password 
    }; 
    $.ajax({ 
     type: "POST", 
     url: base_url + "ajax.php?test/json", 
     data: form_data, 
     success: function(response) 
     { 
      /*response = '[{"Language":"jQuery","ID":"1"},{"Language":"C#","ID":"2"}, 
          {"Language":"PHP","ID":"3"},{"Language":"Java","ID":"4"}, 
          {"Language":"Python","ID":"5"},{"Language":"Perl","ID":"6"}, 
          {"Language":"C++","ID":"7"},{"Language":"ASP","ID":"8"}, 
          {"Language":"Ruby","ID":"9"}]'*/ 
      console.log(response); 

     var json_obj = $.parseJSON(response);//parse JSON 

      var output="<ul>"; 
      for (var i in json_obj) 
      { 
       output+="<li>" + json_obj[i].Language + ", " + json_obj[i].ID + "</li>"; 
      } 
      output+="</ul>"; 

      $('span').html(output); 
     }, 
     dataType: "json"//set to JSON  
    })  
} 
+0

感謝您的幫助。我已經更新了這個問題。 – Tomas

0

我探頭控制檯

{ 
     data = { 
      "items": [ 
       { 
        "id": 1, 
        "status": "active", 
        "price": "300", 
        "size": { 
         "width": 12, 
         "height": 12 
         }, 
       "english": { 
        "name": "My new item", 
        "description": "My item description" 
       } 
      }, 
      { 
       "id": 2, 
       "status": "active", 
       "price": "560", 
       "size": { 
        "width": 11, 
        "height": 14 
       }, 
       "english": { 
        "name": "My new item 2", 
        "description": "My paint item 2" 
       } 
      } 
     ] 
    } 
} 




for(i=0; i< data.items.length; i++) 
{ 
console.log('id: '+ data.items[i].id + ' , status: '+data.items[i].status+ ' , price: '+data.items[i].price) 

console.log('width: '+data.items[i].size.width + ' , heigth: '+data.items[i].size.height); 

console.log('name: '+data.items[i].english.name+ ' , Description: '+data.items[i].english. description); 
} 

我的工作