2012-06-02 50 views
0

我想操縱從PHP文件調用的數組。它發出從jQuery中使用PHP數組

[{ 
    "description": "Intel H67 Socket 1155 Motherboard", 
    "price": "144.99"}, 
{ 
    "description": "Thermaltake WO319RU 850 Watt PSU Modular", 
    "price": "169.99"}, 
{ 
    "description": "LG GH24NS70 SATA DVD Burner", 
    "price": "39.99"}, 
{ 
    "description": "eVGA GTX 480 1536MB GDDR5", 
    "price": "299.99"}] 

這是我的jQuery

$(document).ready(function() { 
function get() { 
    var postdata = $('#scu').val(); 
    $.post('data.php', {scu:postdata}, function(output) { 
     $('#output').append(output); 
    }); 
    } 
$('#scu').keyup(get); 
}); 
//#scu is a textbox 
//#output is an empty div 

如果我這樣稱呼它它顯示了整個陣列;如果我這樣稱呼它output[0]我會得到[;如果我這樣稱呼它output[0].pric E I得到一個unknown' error.

回答

0
$.post('data.php', {scu:postdata}, function(output) { 
     // looping over output 
     $.each(output, function(index, obj) { 
     // obj contains each object eg. 
     // { 
     // "description": "Intel H67 Socket 1155 Motherboard", 
     // "price": "144.99" 
     // } 

     console.log(obj.description); 
     console.log(obj.price); 
     // to append to textbox do something like this 
     $('#scu').append(obj.description); // and so on 
    }); 
}, 'json'); // you need to put dataType here as json, as output is json 
      // you don't need $.parseJSON, because dataType json will 
      // parse it for you 
+0

感謝那個偉大工程。 – user1114060

0
$(document).ready(function() { 
function get() { 
    var postdata = $('#scu').val(); 
    $.post('data.php', {scu:postdata}, function(output) { 
     var objects = jQuery.parseJSON(output); // obj will contain the array of objects you need 
     alert(objects[0].price); 
     $('#output').append(output); 
    }); 
    } 
$('#scu').keyup(get); 
}); 
+0

你真棒,謝謝。 – user1114060