2015-12-21 58 views
0

我想顯示我從PHP服務器獲取的JSON數組,作爲HTML中的列表。我使用的代碼循環遍歷數組,但是當我用變量替換數組時它不起作用。將JSON數組顯示爲html列表

$(document).ready(function(){ 
 
\t $(document).bind('deviceready', function(){ 
 
\t \t //Phonegap ready 
 
\t \t onDeviceReady(); 
 
\t }); 
 

 
\t var ownproducts = $('#ownproducts'); 
 

 
\t $.ajax({ 
 
\t \t url: 'MYURL', 
 
\t \t dataType: 'jsonp', 
 
\t \t jsonp: 'jsoncallback', 
 
\t \t timeout: 5000, 
 
\t \t success: function(data, status){ 
 
\t \t \t $.each(data, function(i,item){ 
 
\t \t \t \t var products = '<br>'+item.item; 
 
\t \t \t \t  var ul = $('<ul>').appendTo('body'); 
 
\t \t \t \t var json = { items: ['Banana','Cherry','Apple','Strawberry','Pear','Pineapple'] }; 
 
\t \t \t \t $(json.items).each(function(index, item) { 
 
\t \t \t \t \t ul.append($(document.createElement('li')).text(item)); 
 
\t \t \t \t }); 
 

 
\t \t \t \t 
 
\t \t \t 
 
\t \t \t \t ownproducts.append(products); 
 
\t \t \t }); 
 
\t \t }, 
 
\t \t error: function(){ 
 
\t \t ownproducts.text('Error Message'); 
 
\t \t } 
 
\t }); 
 
});

所以我從我的數據庫中包含數據的JSON文件,item.item包含數組但是當我替換此:

var json = { items: ['Banana','Cherry','Apple','Strawberry','Pear','Pineapple'] }; 

爲:

var json = { items: item.item }; 

或者:

var json = { items: products }; 

它不起作用(不顯示任何JavaScript相關的東西)。

編輯: 我試圖通過PHP

<?php 
header('Content-type: application/json'); 

require 'config.php'; 
$con = mysqli_connect($url,$username,$password,$database); 

// Check connection 
if (mysqli_connect_errno()) 
    { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 

$userid = $_GET['userID']; 


mysqli_select_db($con, $database); 

$sql = "SELECT shoppingListID AS id, shoppingListUserID AS userid, shoppingCheckBox AS checkbox, shoppingItem AS item, shoppingDate AS date 
FROM shoppinglist 
WHERE shoppingListUserID='$userid' 
ORDER BY shoppingDate DESC"; 
$result = mysqli_query($con,$sql) or die ("Query error: " . mysqli_error()); 

$records = array(); 

while($row = mysqli_fetch_assoc($result)) { 
    $records[] = $row; 
} 

mysqli_close($con); 

echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');'; 
?> 

的ShoppingItem field包含["Tomatos","Apples","Mangos","Bananas"]的SQL陣列從一個單一的用戶返回多個shoppinglists得到從我的數據庫的一些項目,我想上顯示shoppinglists與列表中的每個列表的項目卡片。

有人有什麼建議嗎?我很感激幫助。

+0

你確定你從數據庫中獲取正確的JSON? 'item'鍵是否存在?控制檯中是否有任何錯誤? – Cristy

+0

爲什麼不做'$ .each(json.items,function(index,item){'而不是'$(json.items).each(function(index,item){' – VIDesignz

+0

)另外,你不應該使用'item '兩次,因爲它們是嵌套循環 – VIDesignz

回答

0

讓我假設你的JSON端點事實上確實返回正確的數據 - 在這種情況下訪問你「已經標示MYURL什麼生成文本(我相信!):

jsoncallback({"items":["Banana","Cherry","Apple","Strawberry","Pear","Pineapple"]}) 

然後我們可以移動在你的邏輯,其中包括在這個回調函數:?

function (data, status) { 
    $.each(data, function (i, item) { 
     var products = "<br>" + item.item; 
     var ul = $("<ul>").appendTo("body"); 
     var json = { 
      items: ["Banana", "Cherry", "Apple", "Strawberry", "Pear", "Pineapple"] 
     }; 
     $(json.items).each(function (index, item) { 
      ul.append($(document.createElement("li")).text(item)); 
     }); 
     ownproducts.append(products); 
    }); 
} 

什麼是這裏的問題有很多,第一是,你可能不應該是迭代過data,因爲這是不是你的陣列。相反,你應該迭代超過data.items

第二個是你應該創建HTML而不是創建大量的DOM東西。你可以用香草JS的Array.prototype.mapArray.prototype.join功能,而不是委託這JQuery的:它是JS規範的一部分,這是充分的:

function (data, status) { 
    var html = '<ul><li>' + data.items.join('</li><li>') + '</li></ul>'; 
    $(html).appendTo('body'); 
} 
+0

這不是真正的增加節點的最好方法,附加它們是昂貴的一點,最好在循環之外進行,參見http:/ /allthingscraig.com/blog/2012/09/28/best-practice-appending-items-to-the-dom-using-jquery/ and http://www.bennadel.com/blog/2281-jquery-appends-多元件-使用高效的文檔片段。htm – Basic

+0

首先感謝您的快速回復。我剛開始使用JavaScript,所以我不知道做什麼是最好的方式。如果我正確理解你,你說我可以用'data.items.join'函數替換:'function(data,status){}'? –

+0

@StefSpakman是的,第二個「盒子」是代碼的第一個「盒子」(來自您的帖子)的替代替代品:它們都定義了匿名函數。我的一般建議是,如果你「剛剛開始」,就是要明白JavaScript中沒有太多「魔力」。學習不同類型的東西,你可以用'typeof'來詢問:typeof「x」==「string」','typeof function(){} ==「function」'等等。學習[environment]( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects)。 –