【问题标题】:How can I access ajax response data in global object with jquery? [duplicate]如何使用 jquery 访问全局对象中的 ajax 响应数据? [复制]
【发布时间】:2019-07-28 18:51:07
【问题描述】:

我已经厌倦了这段代码,但我可以访问资产变量中的 ajax 响应数据,我该如何访问它。

const JSONURL = 'json';
var assets = {};

$(function() {
  $.ajax({
    url: `${JSONURL}/assets.json`,
    type: "GET",
    success: function(data) {
      assets.data
    }
  })
});

console.log(assets);

【问题讨论】:

  • 你能把问题编辑得更清楚吗?无论是描述还是您的代码 sn-p 都无法明确说明您想要达到的结果
  • 我猜你的意思是assets = data,而不是assets.data
  • 人们试图帮助您理解语句assets.data 什么都不做,这在不考虑执行ajax 操作的情况下是正确的。这是一个无所事事的声明。

标签: javascript jquery ecmascript-6


【解决方案1】:

如果您的 api 响应是 JSON,那么您只需编辑

success: function(data) {
      assets.data = data
    }

您还可以将assets 对象与窗口对象绑定,以使assets 成为全局范围

【讨论】:

  • 不错的方法,但我想添加没有像 assets.add() 或 assets.push() 这样的任何键
  • assets.data = data这个语句没有使用任何键@Nipu
  • 没有任何钥匙我无法获得价值
【解决方案2】:

您可以使用Custom Event。在这种情况下,您希望在 ajax 成功时触发自定义事件。把它想象成一个事件,你定义。在这种情况下,让我们在窗口对象上触发一个名为my-first-fancy-custom-event 的自定义事件。然后另一方面,您添加事件侦听器(与任何其他事件一样),但在这种情况下,您侦听您定义的名称,再次是 my-first-fancy-custom-event

window.addEventListener(
  "my-first-fancy-custom-event", 
  function(event) {
    // you will only need assets or event.detail
    // this is just to show both ways to get the data
    // chose one also in the ajax success method
    // my personal choice is to avoid global variables like assets
    console.log('assets: ', assets);
    console.log('event.detail: ', event.detail);
  }
);



const JSONURL = 'json';
var assets = {};

$(function() {
  $.ajax({
    url: `${JSONURL}/assets.json`,
    type: "GET",
    success: function(data) {
      // fire custom event here passing the data in detail object
      // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
      // for more details
      assets = data; // so either set the data to the global assets variable
      window.dispatchEvent(
        new CustomEvent(
          "my-first-fancy-custom-event",
          { detail: { myData: data } } // just add here and empty object => {}
                                       // if you chose global variable
        );
      );
    }
  })
});

【讨论】:

  • 我怀疑 OP 会查看这个答案,试图找出代码更新全局 assets 变量的位置,这是问题的主题。
  • 是的,谢谢@Pointy!我刚刚想通了。我得更新了
  • 我不满意
猜你喜欢
  • 1970-01-01
  • 2022-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-16
  • 2016-05-09
  • 1970-01-01
相关资源
最近更新 更多