0

我正在尝试操作从 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得到一个unknown' error.

4

2 回答 2

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
于 2012-06-02T04:10:54.520 回答
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);
});
于 2012-06-02T04:12:28.700 回答