简体   繁体   English

需要存储对全局变量的ajax响应

[英]need to store ajax response to a global variable

I am using ajax to get some values from a database. 我正在使用ajax从数据库中获取一些值。 In my java script file I have a global variable that some functions need to access it. 在我的Java脚本文件中,我有一些函数需要访问它的全局变量。 I need to fill that variable from the values from the database. 我需要从数据库中的值填充该变量。 When I use ajax then the variable stays empty. 当我使用ajax时,变量保持为空。 If I use the async:false in my ajax code I get that warning message in my browser's dev tools: 如果我在ajax代码中使用async:false ,则会在浏览器的开发工具中收到该警告消息:

jquery-3.2.1.min.js:4 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. jquery-3.2.1.min.js:4 [Deprecation]不赞成在主线程上使用同步XMLHttpRequest,因为它对最终用户的体验有不利影响。 For more help, check https://xhr.spec.whatwg.org/ . 如需更多帮助,请访问https://xhr.spec.whatwg.org/

Moreover using the above it doesn't fill the variable resulting to errors in the other functions. 此外,使用上面的方法不会填充变量,导致其他函数出错。 Plus, from what I read this is deprecated and should not be used in any circumstances. 另外,根据我的阅读,此内容已被弃用,在任何情况下均不应使用。

my code 我的代码

var array ={};
var flag = 'true';
        $.ajax({
            url: "name.php",
            method: "post",
            data:{flag:JSON.stringify(flag)},
            success: function(data) {
                array = JSON.parse(data);

            },
             async: false,
            error: function(xhr, ajaxOptions, thrownError) {
            console.log(thrownError);
            }
        });

What, basically I'm trying to do, is to fill the array variable and make it an proper array. 基本上,我想做的是填充数组变量并使之成为合适的数组。

the data from the the database is like this 来自数据库的数据是这样的

{ 'something': { 'act1': 'act1a','act2': 'act2a'}, 'something2': { 'act1': 'act1a','act2': 'act2a'} }

anyone have any suggestions on how to achieve that? 有人对如何实现这一目标有任何建议吗?

PS: I need to fill a variable with the ajax response which will be accessible by other functions... not Convert a JSON Object into Javascript array...Im retrieving the data in string format PS:我需要用ajax响应填充一个变量,其他函数可以访问该变量...不能将JSON对象转换为Javascript数组...正在以字符串格式检索数据

Based on your question and code, I think you are trying to access your array object before it is loaded with data. 根据您的问题和代码,我认为您正在尝试在array对象加载数据之前对其进行访问。 First of all, you will need to remove async:false . 首先,您需要删除async:false You want this to be asynchronous. 您希望这是异步的。 That's the nature of ajax. 那就是ajax的本质。 Secondly, make sure you "do stuff" with array after the ajax call completes. 其次,请确保在ajax调用完成array 进行 “处理”。 For example, this will not work: 例如,这将不起作用:

var array ={};
var flag = 'true';
$.ajax({
    url: "name.php",
    method: "post",
    data:{flag:JSON.stringify(flag)},
    success: function(data) {
        array = JSON.parse(data);
    },
    error: function(xhr, ajaxOptions, thrownError) {
        console.log(thrownError);
    }
});
//DO STUFF WITH array here.. will not work

But this will work: 但这将起作用:

var array ={};
var flag = 'true';
$.ajax({
    url: "name.php",
    method: "post",
    data:{flag:JSON.stringify(flag)},
    success: function(data) {
        array = JSON.parse(data);
        //DO STUFF WITH array here..
    },
    error: function(xhr, ajaxOptions, thrownError) {
        console.log(thrownError);
    }
});

One more thing to consider here - It's common practice to create a function outside your ajax success function to do something with your data ( array ), and call that function from inside your success function: 这里要考虑的另一件事-通常的做法是 ajax success函数之外创建一个函数以对数据( array )做一些事情,然后从success函数内部调用该函数:

var array ={};
var flag = 'true';
$.ajax({
    url: "name.php",
    method: "post",
    data:{flag:JSON.stringify(flag)},
    success: function(data) {
        array = JSON.parse(data);
        doStuffWithArray(array);
    },
    error: function(xhr, ajaxOptions, thrownError) {
        console.log(thrownError);
    }
});

function doStuffWithArray(myArray) {
    //DO STUFF HERE...
}

So lets say you have an ajax call that you are making to and endpoint, whose response you may want to use at a later time, not immediately upon the success of the ajax call, for whatever reason. 因此,假设您有一个要进行的ajax调用并终结点,无论出于何种原因,您可能希望稍后使用它的响应,而不是在ajax调用成功后立即使用。 One way to do that is to pass around the promise/deferred that the $.ajax method returns. 一种方法是绕过$.ajax方法返回的承诺/延期。 With this object you can attach any of the promise/deferred methods for handling the resolution or rejection of the promise. 有了这个对象,您可以附加任何promise / deferred方法来处理promise的解决或拒绝。 For instance: 例如:

 //first we'll create a dummy deferred. we will pretend that this is our ajax call. in actual code this would look something like //var dummyDeferred = $.ajax(...); var dummyDeferred = $.Deferred(); //lets say, maybe you do want something to happen immediately upon the request success. you can do that. dummyDeferred.then(function(data){ console.log("immediate then", data); }); //now lets say that the ajax finishes, you should see the console log as you'd expect from the above then() dummyDeferred.resolve("hello!"); //now lets say that some time later, you want to use that result inside another method to do something. to do that you can simply attach another then() to the promise/deferred //we'll use a timeout to simulate later usage of the promise/deferred setTimeout(function(){ doOtherStuff(dummyDeferred); }, 5000); function doOtherStuff(promise) { //maybe you want to take the data response and put it on the page some how. you can! promise.then(function(data){ $(document.body).append(data); }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

var array;
var flag = 'true';
        $.ajax({
            url: "name.php",
            method: "post",
            data:{flag:JSON.stringify(flag)},
            success: function(data) {
                array = JSON.parse(data);
                function_ThatNeeds_Thearray();

            },
             async: false,
            error: function(xhr, ajaxOptions, thrownError) {
            console.log(thrownError);
            }
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM