JQuery - 将 ajax 响应存储到全局变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/905298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery - Storing ajax response into global variable
提问by Charles Guilbert
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.
我仍然是 jQuery 和 ajax 场景的新手,但我有一个 $.ajax 请求执行 GET 来检索一些 XML 文件(~6KB 或更少),但是在用户在该页面上花费的时间里,XML 内容应该不/不会改变(这个设计我不能改变,我也无权更改 XML 文件,因为我正在从其他地方读取它)。因此,我有一个全局变量,我将响应数据存储到其中,并且对数据的任何后续查找都在此变量上完成,因此不需要进行多个请求。
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.
鉴于 XML 文件可以增加这一事实,我不确定这是最佳实践,而且来自 java 背景,我对全局公共变量的想法通常是禁忌。
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?
所以我的问题是是否有更好的方法来做到这一点,以及如果文件扩展到一些荒谬的文件大小,这是否会导致任何内存问题?
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.
我认为数据可以传递到 xml 对象内的一些 getter/setter 类型函数中,这将解决我的全局公共变量问题,但仍然提出了是否应该将响应存储在对象本身内部的问题。
For example, what I currently do is:
例如,我目前做的是:
// 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');
采纳答案by Luke Schafer
There's no way around it except to store it. Memory paging should reduce potential issues there.
除了储存它,别无他法。内存分页应该减少那里的潜在问题。
I would suggest instead of using a global variable called 'xml', do something more like this:
我建议不要使用名为 'xml' 的全局变量,而是做一些更像这样的事情:
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;
}};
})();
then access it with:
然后访问它:
$(dataStore.getXml()).find('something').attr('somethingElse');
回答by Charles Guilbert
Here is a function that does the job quite well. I could not get the Best Answer above to work.
这是一个可以很好地完成工作的函数。我无法得到上面的最佳答案。
jQuery.extend({
getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'xml',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
});
Then to access it, create the variable like so:
然后访问它,像这样创建变量:
var results = $.getValues("url string");
回答by Phil Lowe
This worked for me:
这对我有用:
var jqxhr = $.ajax({
type: 'POST',
url: "processMe.php",
data: queryParams,
dataType: 'html',
context: document.body,
global: false,
async:false,
success: function(data) {
return data;
}
}).responseText;
alert(jqxhr);
// or...
return jqxhr;
Important to note: global: false
, async:false
and finally responseText
chained to the $.ajax
request.
重要的是要注意:global: false
,async:false
最后responseText
链接到$.ajax
请求。
回答by Dom
You don't have to do any of this. I ran into the same problem with my project. what you do is make a function call inside the on success callback to reset the global variable. As long as you got asynchronous javascript set to false it will work correctly. Here is my code. Hope it helps.
你不必做任何这些。我的项目遇到了同样的问题。您要做的是在成功回调中进行函数调用以重置全局变量。只要您将异步 javascript 设置为 false,它就会正常工作。这是我的代码。希望能帮助到你。
var exists;
//function to call inside ajax callback
function set_exists(x){
exists = x;
}
$.ajax({
url: "check_entity_name.php",
type: "POST",
async: false, // set to false so order of operations is correct
data: {entity_name : entity},
success: function(data){
if(data == true){
set_exists(true);
}
else{
set_exists(false);
}
}
});
if(exists == true){
return true;
}
else{
return false;
}
Hope this helps you .
希望这对你有帮助。
回答by Aidan Fitzpatrick
You might find it easier storing the response values in a DOM element, as they are accessible globally:
您可能会发现将响应值存储在 DOM 元素中更容易,因为它们可以全局访问:
<input type="hidden" id="your-hidden-control" value="replace-me" />
<script>
$.getJSON( '/uri/', function( data ) {
$('#your-hidden-control').val( data );
} );
</script>
This has the advantage of not needing to set async to false. Clearly, whether this is appropriate depends on what you're trying to achieve.
这具有不需要将 async 设置为 false 的优点。显然,这是否合适取决于您要实现的目标。
回答by vortex
your problem might not be related to any local or global scope for that matter just the server delay between the "success" function executing and the time you are trying to take out data from your variable.
您的问题可能与任何本地或全局范围无关,只是“成功”函数执行与您尝试从变量中取出数据之间的服务器延迟。
chances are you are trying to print the contents of the variable before the ajax "success" function fires.
您可能正在尝试在 ajax“成功”函数触发之前打印变量的内容。
回答by DarthVader
function getJson(url) {
return JSON.parse($.ajax({
type: 'GET',
url: url,
dataType: 'json',
global: false,
async: false,
success: function (data) {
return data;
}
}).responseText);
}
var myJsonObj = getJson('/api/current');
This works!!!
这有效!!!
回答by Edmhs
function get(a){
bodyContent = $.ajax({
url: "/rpc.php",
global: false,
type: "POST",
data: a,
dataType: "html",
async:false
}
).responseText;
return bodyContent;
}
回答by stvn
Ran into this too. Lots of answers, yet, only one simple correct one which I'm going to provide. The key is to make your $.ajax call..sync!
也遇到了这个。很多答案,然而,我将提供一个简单正确的答案。关键是让你的 $.ajax 调用..sync!
$.ajax({
async: false, ...
回答by CityPickle
I really struggled with getting the results of jQuery ajax into my variables at the "document.ready" stage of events.
在事件的“document.ready”阶段,我真的很难将 jQuery ajax 的结果放入我的变量中。
jQuery's ajax would load into my variables when a user triggered an "onchange" event of a select box after the page had already loaded, but the data would not feed the variables when the page first loaded.
当用户在页面加载后触发选择框的“onchange”事件时,jQuery 的 ajax 将加载到我的变量中,但在页面首次加载时数据不会提供变量。
I tried many, many, many different methods, but in the end, it was Charles Guilbert's method that worked best for me.
我尝试了很多很多很多不同的方法,但最终,Charles Guilbert 的方法最适合我。
Hats off to Charles Guilbert! Using his answer, I am able to get data into my variables, even when my page first loads.
向查尔斯吉尔伯特致敬!使用他的回答,即使我的页面第一次加载,我也可以将数据放入我的变量中。
Here's an example of the working script:
这是工作脚本的示例:
jQuery.extend
(
{
getValues: function(url)
{
var result = null;
$.ajax(
{
url: url,
type: 'get',
dataType: 'html',
async: false,
cache: false,
success: function(data)
{
result = data;
}
}
);
return result;
}
}
);
// Option List 1, when "Cats" is selected elsewhere
optList1_Cats += $.getValues("/MyData.aspx?iListNum=1&sVal=cats");
// Option List 1, when "Dogs" is selected elsewhere
optList1_Dogs += $.getValues("/MyData.aspx?iListNum=1&sVal=dogs");
// Option List 2, when "Cats" is selected elsewhere
optList2_Cats += $.getValues("/MyData.aspx?iListNum=2&sVal=cats");
// Option List 2, when "Dogs" is selected elsewhere
optList2_Dogs += $.getValues("/MyData.aspx?iListNum=2&sVal=dogs");