简体   繁体   English

Ajax回调以将变量检查为全局变量

[英]Ajax callback to check variables as global

I'm trying to implement a function that after consulting a service brings the variables as global. 我正在尝试实现一个功能,在咨询服务后将变量作为全局变量。

  function ajax_test(str1, callback){  
   $.ajax({ 
     url: '/path/service',
     type: 'POST',
     dataType: "json",
     data: {'vars':$('form').serialize(), 'test':123},
     success: function(data, status, xhr){  
       callback(data);
     }
   });  
}

and I'm trying to call like this: 我试图这样打电话:

ajax_test("str", function(url) {
    //do something with url
    console.log(url);
});

Now, if I just call ajax_test() it returns an error, saying that callback is not a function . 现在,如果我只是调用ajax_test()它将返回一个错误,表示回调不是function

How would be the best way to simply call the function and get the results to use global variables? 简单调用函数并获得使用全局变量的结果的最佳方法是什么?

Edit: I think a good question is: what is a good alternative to async: false? 编辑:我认为一个好问题是:什么是异步的一个很好的替代:错误? How is the best way to implement synchronous callback? 如何实现同步回调的最佳方法?

Edit 2: For now, I'm using $.post() with $.ajaxSetup({async: false}); 编辑2:现在,我将$.post()$.ajaxSetup({async: false}); and it works how I expect. 它按我的预期工作。 Still looking a way I could use with a callback. 仍在寻找一种可用于回调的方法。

Have to set the scope inside the success method. 必须在成功方法内设置范围。 Adding the following should work. 添加以下内容应该可以。

function ajax_test(str1, callback){  
   $.ajax({ 
       url: '/path/service',
       type: 'POST',
       dataType: "json",
       data: {'vars':$('form').serialize(), 'test':123},
       success: function(data, status, xhr){  
           this.callback(data);
       }.bind(this)
   });  
}

As an argument of the ajax_test function, callback is in the scope of the ajax_test function definition and can be called anywhere there, particularly in the success case. 作为ajax_test函数的参数, callbackajax_test函数定义的范围内,可以在任何地方调用,尤其是在success情况下。 Note that calling ajax_test() without arguments will as expected make your code call a function that does not exist, named callback . 请注意,不带参数调用ajax_test()会使您的代码调用不存在的名为callback的函数。

The following sends an Ajax request to the jsFiddle echo service (both examples of callback as anonymous or global function are given in the jsFiddle), and works properly : 下面的代码向jsFiddle回显服务发送一个Ajax请求(在jsFiddle中给出了作为匿名或全局函数的callback示例),并且可以正常工作:

function ajax_test(str1, callback){  
   $.ajax({ 
     url: '/echo/json',
     type: 'POST',
     dataType: "json",
     data: {
        json: JSON.stringify({
        'vars':$('form').serialize(),
        'test':123
       })
     },
     success: function(data, status, xhr){  
       callback(data);
     }
   });  
}

ajax_test("unusedString", function(data){
    console.log("Callback (echo from jsFiddle called), data :", data);
});

Can you check that the webservice you're calling returns successfully ? 您可以检查正在调用的Web服务是否成功返回吗? Here is the jsFiddle, I hope you can adapt it to your need : 这是jsFiddle,希望您可以根据需要进行调整:

https://jsfiddle.net/dyjjv3o0 https://jsfiddle.net/dyjjv3o0

UPDATE: similar code using an object 更新:使用对象的类似代码

function ajax_test(str1) {

  this.JSONFromAjax = null;

  var self = this;

  function callback(data) {
     console.log("Hello, data :", data);
     console.log("Hello, this :", this);
     $("#callbackResultId").append("<p>Anonymous function : " + JSON.stringify(data) + "</p>");
     this.JSONFromAjax = JSON.stringify(data);
  }

  $.ajax({
    url: '/echo/json',
    type: 'POST',
    dataType: "json",
    data: {
      json: JSON.stringify({
        'vars': $('form').serialize(),
        'test': 123
      })
    },
    success: function(data, status, xhr) {
      console.log("Success ajax");
      // 'self' is the object, force callback to use 'self' as 'this' internally.
      // We cannot use 'this' directly here as it refers to the 'ajax' object provided by jQuery
      callback.call(self, data);
    }
  });
}

var obj = new ajax_test("unusedString");
// Right after the creation, Ajax request did not complete
console.log("obj.JSONFromAjax", obj.JSONFromAjax);
setTimeout(function(){
  // Ajax request completed, obj has been updated
  console.log("obj.JSONFromAjax", obj.JSONFromAjax);
}, 2000)

You cannot expect the Ajax request to complete immediately (don't know how it behaves with async: false though, this is why you need to wait for a while before getting the actual response. 您不能期望Ajax请求立即完成(不知道它如何与async: false不过为async: false ,这就是为什么您需要等待一段时间才能获得实际响应。

Updated jsFiddle here : http://jsfiddle.net/jjt39mg3 在这里更新了jsFiddle: http : //jsfiddle.net/jjt39mg3

Hope this helps! 希望这可以帮助!

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

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