简体   繁体   English

Ajax 调用输出到全局变量

[英]Ajax call Output into global variable

How to assign the output of ajax call to a global variable so that the output can be used outside the ajax call?如何将ajax调用的输出分配给一个全局变量,以便输出可以在ajax调用之外使用?

var filterarray=new Array();
$.ajax({
            type: "GET",
            url: uri,
            dataType : "json",
            contentType : "application/json",           
            data: {
                input:filtervalue
            },  
            cache: false,
            success : function(response) {
                filterarray = response;
                console.log(response);

                });
            },
            error: function(error) { 
                console.log(error);
            }
            });
    }

Let's say you have this simple example from ajax documentation:假设您有一个来自ajax文档的简单示例:

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() {
  $( this ).addClass( "done" );
});

As you see adding the context sets this reference within all callbacks:如您所见,添加context在所有回调context设置this引用:

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings;所有回调中的 this 引用是在设置中传递给 $.ajax 的上下文选项中的对象; if context is not specified, this is a reference to the Ajax settings themselves.如果未指定上下文,则这是对 Ajax 设置本身的引用。

You could also just append your variable to window .您也可以将变量附加到window

You can assign the value to a global variable just like anywhere else in the code.您可以将值分配给全局变量,就像代码中的任何其他地方一样。

var value;

$.ajax().done(function(responseValue) {
    value = responseValue;
});

Although the problem is that this code is asynchronous and you if you try to access the value before call completes, for example right after $.ajax block, the value will be undefined.尽管问题是这段代码是异步的,如果您尝试在调用完成之前访问该值,例如在$.ajax块之后,该值将是未定义的。 The jQuery $.ajax call returns an implementation of Promise, so it's a much better practice to do: jQuery $.ajax调用返回一个 Promise 的实现,所以这是一个更好的做法:

var ajaxPromise = $.ajax(...);
// ...

// here you want to access value form ajax call:
ajaxPromise.done(function(value) {
    // do something with value
});

The great thing about promises is that you can call .done multiple times and it will always resolve with the value , even if it was already used before. .done在于你可以多次调用.done并且它总是会用value解析,即使它之前已经使用过。

Try this:尝试这个:

var result; 
$.ajax({ 
       type: "POST", 
       async: false, 
       url: url, 
       data: postdata, 
       dataType: "json", 
       success: function (data) { 
       result= data; 
   } });
result = jQuery.parseJSON(result);

Here async:false is used to store ajax return value to the global result variable.这里async:false用于将 ajax 返回值存储到全局result变量中。

Let me know these code snippets works or not.让我知道这些代码片段是否有效。

Ajax is asynchronous. Ajax 是异步的。 So response may get after the code execution.所以代码执行后可能会得到响应。

var filterarray=new Array();
$.ajax({
            type: "GET",
            url: uri,
            dataType : "json",
            contentType : "application/json",           
            data: {
                input:filtervalue
            },  
            cache: false,
            success : function(response) {
                filterarray = response;
                // do what ever you want to do with response here.



                });
            },
            error: function(error) { 
                console.log(error);
            }
            });
    }

function getJson(url) { return JSON.parse($.ajax({ type: 'GET', url: url, dataType: 'json', global: false, async:false, data: { filter:value }, success: function(data) { return data; } }).responseText); function getJson(url) { return JSON.parse($.ajax({ type: 'GET', url: url, dataType: 'json', global: false, async:false, data: { filter:value }, success: function(data) { return data; } }).responseText); } }

Above piece of code solved my issues上面的一段代码解决了我的问题

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

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