2011-06-25 18 views
4

我想保存在一个阵列中的每个JSON响应我没有写这样的方式保存JSON响应到阵列

$(document).ready(function() { 
    var saveJson = []; 
    var jsonResponse = getjsonResponse() 
         //something with $get function response json format 
    saveJson = saveToArray(jsonResponse.SearchResults); 

    var saveToArray = function(array){ 
     $.each(array,function(i,data){ 
      saveJson.push(data); 
     }); 
    }; 
}); 

但似乎是我的代码不能正常工作saveJson越来越不确定我怎样才能克服这个?只需要将json响应追加到一个数组对象。

我的样本响应看起来像

"SearchResults":[ 
      { 
      "TypeFlag":"W", 
      "HashCode":"66093013", 
      "ShortenKey":"http:///k", 
      "Title":"Yahoo! \u003cspan class=\"search-result-highlight\"\u003eSearch\u003c/span\u003e - Web \u003cspan class=\"search-result-highlight\"\u003eSearch\u003c/span\u003e", 
      "Description":"The \u003cb\u003esearch\u003c/b\u003e engine that helps you find exactly what you\u0027re looking for. Find the most relevant information, video, images, and answers from all across the Web.", 
      "Url":"http://search.yahoo.com/", 
      "LastUpdateOn":"6/21/2011 1:01:11 PM", 
      "PageRank":1, 
      "ThumbImageUrl":"" 
      }, 
     { 
      "TypeFlag":"W", 
      "HashCode":"48394089", 
      "ShortenKey":"http:///5i", 
      "Title":"Lijit | Advertising Services, Audience Analytics and Publisher ...", 
      "Description":"I’ve been using Lijit as my site \u003cb\u003esearch\u003c/b\u003e for several years and the understanding I get about my audience is critical to knowing what my readership is interested in and ...", 
      "Url":"http://www.lijit.com/", 
      "LastUpdateOn":"6/22/2011 11:31:41 PM", 
      "PageRank":10, 
      "ThumbImageUrl":"" 
     } 
] 

感谢

+0

您的代码并没有真正意义。您分配一个函数'jsonResponse',然后将它传递给'saveToArray',将该函数视为数组。如果你真的调用了一个函数来获得响应,我假设你发出了一个Ajax请求。 Ajax是**异步**。您必须使用处理响应的回调。我建议你看看一些Ajax示例。 –

+0

你的示例json是什么? – naveen

+0

好的,我将使用我的json示例对象编辑 – Gayan

回答

2
function(array){ 
    $.each(array,function(i,data){ 
     saveJson.push(data); 
    }); 
}; 

返回undefined。尽管将数据推入saveJson,但您的“saveJson = saveToArray(jsonResponse)”将saveJson重新分配为undefined

你可能有:

function(array){ 
    var ret = []; 
    $.each(array,function(i,data){ 
     ret.push(data); 
    }); 
    return ret; 
}; 
+0

我接受了这个,但不是我的问题的最佳答案。 – Gayan

0

您的JSON是不是一个数组,你确实有包含“SearchResult所”一个数组的对象,所以你要传递的,而不是整个对象:

saveJson = saveToArray(jsonResponse.SeachResults); //change this line 

(假设jsonResponse定义)