Javascript push()函数没有添加到数组

时间:2014-06-16 00:43:54

标签: jquery

我已经看过其他类似的问题,但到目前为止似乎没有一个适用的问题。

我正在尝试从数据库中获取的数据生成一个字符串,并将其推送到Pickachoose jquery库的数组中,该库需要JSON,如下所示:

var a = [
  {"image":"../../1.jpg","caption":"Any donation is appreciated. PikaChoose is free to use!","link":"http://pikachoose.com","title":"Image 1"},
  {"image":"../../2.jpg","caption":"Be sure to check out <a href=\"http://www.pikachoose.com\">PikaChoose.com</a> for updates.","link":"http://pikachoose.com","title":"Image 2"},
  {"image":"../../3.jpg","caption":"You can use any type of html you want with PikaChoose","link":"http://pikachoose.com","title":"Image 3"}
 ];
$(".pikachoose").PikaChoose({data:a});

如果我像这样对它进行硬编码,则上述工作正常。

但是,我使用以下代码从mySQL数据库获取数据:

    var a = [];

    $.getJSON("search.cfc?method=x&returnformat=json&queryformat=column",{"id":id},function(res,code){
         for (var i = 0; i<res.ROWCOUNT; i++) {
              var img = res.DATA.IMAGE[i].toLowerCase();
              var cap = res.DATA.CAPTION[i].toLowerCase();
              var lnk = res.DATA.LINK[i].toLowerCase();
              var ttl = res.DATA.TITLE[i].toLowerCase(); 
              var str = '{"image":"' + img + '","caption":"' + cap + '","link":"' + lnk + '","title":"' + ttl + '"}';  
              // str gives, e.g., {"image":["/images/website/retailers/logos/78/serena.jpg"],"caption":["ghsf"],"link":["jhghdfghd"],"title":["rtetuye"]}
              a.push(str); // problem here; doesn't push the string
         }

 });

所以基本上没有推送数组。

1 个答案:

答案 0 :(得分:0)

你应该推送对象而不是字符串。将var str = ...更改为

var str = {
    "image": img,
    "caption": cap,
    "link": lnk,
    "title": ttl
};