格式化从jQuery自动完成返回的json对象

时间:2010-12-07 15:41:56

标签: jquery json

我正在使用此jQuery autocomplete plugin

我希望我的返回数据是json格式。

searchPopup:function(){
     $("input.searchField").autocomplete("myjson1.json", {
      dataType: 'json',
      parse: function(data) {
        $.each(data.productList, function(k, v) {
        jQuery(".searchPanel").append("<div class="+k+"><h2>"+k+"</h2><ul class="+k+"></ul</div>");
         $.each(v, function(k1, v1) {
          $.each(v1, function(k2, v2) { 
           jQuery("ul."+k).append("<li>"+v2+"</li>");
          });
         });
       });
      },
      max: 50
     }); 

   }

当我解析这些数据时,它会发出错误

  

c.split不是函数

如何解决这个问题?

{ 
"productList" : { 
    "Byproducts" : [ 
    {
     "brand":"Bosch",
     "productname":"Jigsaw blade",
     "price":50
    },
    {
     "brand":"Bosch1",
     "productname":"Jigsaw blade",
     "price":51
    },
    {
     "brand":"Bosch2",
     "productname":"Jigsaw blade",
     "price":52
    },
    {
     "brand":"Bosch3",
     "productname":"Jigsaw blade",
     "price":53
    }
     ],
    "Spareparts" : [ 
    {
     "brand":"BoschS1",
     "productname":"Jigsaw blade",
     "price":50
    }
   ],
    "Bybrand" : [ 
    {
     "brand":"BoschBY"
    }      
   ],
    "Bycategory" : [{
     "brand":"BoschBYc",
     "productname":"Jigsaw blade",
     "price":50
    } ]
 }
}

1 个答案:

答案 0 :(得分:2)

我赞成使用不同的方式(使用jQueryUI插件):

  $('input.searchField').autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                url: "myjson1.json",
                contentType: "application/json; charset=utf-8",
                dataType: "json"
                success: function (data) {
                    response(
                    //this saves from having to make a new type to return. It's a                          standard jQuery function.
                    $.map(data.Byproducts, function (item) {
                        return {
                            label: item.productname + ' ' + item.price,
                            value: item.brand
                        }
                    }))
                }
            })
        }