JQuery - 将 ajax 响应存储到全局变量中 [英] JQuery - Storing ajax response into global variable

查看:27
本文介绍了JQuery - 将 ajax 响应存储到全局变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是 jQuery 和 ajax 场景的新手,但我有一个 $.ajax 请求执行 GET 以检索一些 XML 文件(~6KB 或更少),但是在用户在该页面上花费的时间XML 内容不应该/不会改变(这个设计我不能改变,我也无权更改 XML 文件,因为我从其他地方读取它).因此,我有一个将响应数据存储到其中的全局变量,并且对数据的任何后续查找都在此变量上完成,因此不需要发出多个请求.

Im still somewhat of a newbie on jQuery and the ajax scene, but I have an $.ajax request performing a GET to retrieve some XML files (~6KB or less), however for the duration the user spends on that page that XML content should not / will not change (this design I cannot change, I also don't have access to change the XML file as I am reading it from somewhere else). Therefore I have a global variable that I store the response data into, and any subsequent look ups on the data are done on this variable so multiple requests don't need to be made.

鉴于 XML 文件可以增加这一事实,我不确定这是最佳做法,而且来自 java 背景,我对全局公共变量的想法通常是不可以的.

Given the fact that the XML file can increase, Im not sure this is the best practice, and also coming from a java background my thoughts on global public variables are generally a no-no.

所以我的问题是是否有更好的方法来做到这一点,以及如果文件扩展到一些荒谬的文件大小,这是否会导致任何内存问题?

So the question I have is whether there might be a better way to do this, and a question on whether this causes any memory issues if the file expands out to some ridiculous file size?

我认为可以将数据传递到 xml 对象内的一些 getter/setter 类型函数中,这将解决我的全局公共变量问题,但仍然提出了是否应该将响应存储在对象本身内部的问题.

I figure the data could be passed into a some getter/setter type functions inside the xml object, which would solve my global public variable problems, but still raises the question on whether I should store the response inside the object itself.

例如,我目前做的是:

// top of code
var xml;
// get the file
$.ajax({
  type: "GET",
  url: "test.xml",
  dataType: "xml",
  success : function(data) {
    xml = data;
  }
});
// at a later stage do something with the 'xml' object
var foo = $(xml).find('something').attr('somethingElse');

推荐答案

除了存储它之外别无他法.内存分页应该可以减少那里的潜在问题.

There's no way around it except to store it. Memory paging should reduce potential issues there.

我建议不要使用名为 'xml' 的全局变量,而是做一些类似这样的事情:

I would suggest instead of using a global variable called 'xml', do something more like this:

var dataStore = (function(){
    var xml;

    $.ajax({
      type: "GET",
      url: "test.xml",
      dataType: "xml",
      success : function(data) {
                    xml = data;
                }
    });

    return {getXml : function()
    {
        if (xml) return xml;
        // else show some error that it isn't loaded yet;
    }};
})();

然后访问它:

$(dataStore.getXml()).find('something').attr('somethingElse');

这篇关于JQuery - 将 ajax 响应存储到全局变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆