【问题标题】:way to save Json response in to array将 Json 响应保存到数组中的方法
【发布时间】:2011-09-22 14:19:58
【问题描述】:

我想将每个 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":""
      }
]

谢谢

【问题讨论】:

  • 您的代码没有真正的意义。您分配一个函数jsonResponse,然后将其传递给saveToArray,将该函数视为数组。如果您实际上是调用 a 函数来获取响应,我假设您发出了 Ajax 请求。 Ajax 是异步的。您必须使用处理响应的回调。我建议你看看一些 Ajax 示例。
  • 好的,我将使用我的 json 示例对象进行编辑
  • getjsonResponse 是做什么的?如果它有一个异步请求,你需要一个回调函数来处理它。 (不只是假设它在下一行加载)
  • @digitalFresh 这是 jquery $get 函数获取 json 格式响应

标签: javascript jquery json


【解决方案1】:
function(array){
    $.each(array,function(i,data){
        saveJson.push(data);
    });
};

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

你可能有:

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

【讨论】:

    【解决方案2】:

    您的 JSON 不是数组,实际上您在“SearchResults”中有一个包含数组的对象,因此您必须传递它而不是整个对象:

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

    (假设 jsonResponse 已定义)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      相关资源
      最近更新 更多