【问题标题】:Process data from return by an ajax request, but outside the callback function处理 ajax 请求返回的数据,但在回调函数之外
【发布时间】:2011-04-15 21:33:58
【问题描述】:

我有这个代码。

/*
   Get the source of the data.
*/

if (if_the_source_is_an_url) {

  $.getJSON(url_here, function(returnedData){ theData = returnedData; });

}

/*
   Here we have the default processing of theData.
*/

所以我需要如果用户提供一个 url,返回的数据将被处理但在回调函数之外,因为我需要重用数据处理代码。所以,我提出了这个想法。

  • 使用中断命令 $.getJSON(url_here, function(returnedData){ theData = returnedData; break;});
  • 更改为 $.ajax 请求,但使用 异步:假
  • 只需将数据处理放在一个 函数并从
    回调函数。

    if (url) $.getJSON(url_here, function(returnedData){ customFunction(returnedData); }); else customFunction(defaultData);

任何想法是否可行(我没有测试它,因为我不在家),或者有更好的做法吗?

【问题讨论】:

  • 我认为第三个选项(从回调中调用数据处理函数)是最好的方法。
  • 我会接受你的解决方案。谢谢

标签: jquery ajax function callback getjson


【解决方案1】:

使用jQuery.ajaxComplete 附加处理程序/函数以过滤/转换/等您的数据。您在此处附加的句柄将为您的所有 ajax 请求调用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 2017-10-01
    • 1970-01-01
    • 2013-03-28
    • 2013-01-08
    相关资源
    最近更新 更多