JQuery的AJAX功能工作,但不能正确地返回变量 [英] JQuery ajax function works but can't return the variable correctly

查看:133
本文介绍了JQuery的AJAX功能工作,但不能正确地返回变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有正确的函数runAjax的功能。不幸的是,我挣扎着回到我从阿贾克斯查询中获得的价值。

AJAX的函数将里面的内容或错误XML标签变量结果的返回值。

如果我提醒结果变量的AJAX功能,它会提醒正确的值内(即,如果里面内容的XML值发表它提醒出版)。

但是,如果我提醒从runAjax函数它警告的对象,而不是内部变量结果,这在上面的例子中被发布的值返回值

 函数runAjax(data_obj){
  返回$阿贾克斯({
      网址:/ ajax.php
      数据类型:XML,
      数据:data_obj,
      成功:功能(数据){
        //格式结果
        VAR XML;
        如果(typeof运算数据==字符串){
          XML =新的ActiveXObject(Microsoft.XMLDOM);
          xml.async = FALSE;
          xml.loadXML(数据);
        } 其他 {
          XML =数据;
        }
        VAR的结果;
        如果($(错误,XML)的.text()){
          结果= [$(错误,XML)的.text()];
        } 其他{
          结果= [
            $(内容,XML)的.text()
          ]。
        }
      警报(结果); //提醒正确的字符串,例如发表了
      返回结果;
      }
    });
  }
  $('ul.content李span.changeable)。点击(函数(五){
    即preventDefault();
    。VAR method_set = $(本).parent()ATTR(类);
    。VAR id_set = $(本).parent()父()找到('li.id跨度)HTML();
    VAR用户= $(本);
    VAR的结果= runAjax({方法:method_set,ID:id_set});
    警报(结果); //警报对象未发布

  });
 

我敢肯定它是与我返回变量的方式,但我不能弄明白。任何投入将是非常美联社preciated。

问候 卢克

更新: 这是修订后的code的作品感谢各界投入的人如下:

 函数runAjax(data_obj,回调){
    $阿贾克斯({
      网址:/ ajax.php
      数据类型:XML,
      数据:data_obj,
      成功:功能(数据){
        //格式结果
        VAR XML;
        如果(typeof运算数据==字符串){
          XML =新的ActiveXObject(Microsoft.XMLDOM);
          xml.async = FALSE;
          xml.loadXML(数据);
        } 其他 {
          XML =数据;
        }
        VAR的结果;
        如果($(错误,XML)的.text()){
          结果= [$(错误,XML)的.text()];
        } 其他{
          结果= [
          $(内容,XML)的.text()
          ]。
        }
        如果(typeof运算(回调)==功能){
          回调(结果);
        }
      }
    });
  }
  $('ul.content李span.changeable)。点击(函数(五){
    即preventDefault();
    。VAR method_set = $(本).parent()ATTR(类);
    。VAR id_set = $(本).parent()父()找到('li.id跨度)HTML();
    VAR用户= $(本);
    runAjax({
      方法:method_set,
      ID:id_set
    },
    功能(结果){
      $(用户)的.html(result.join('')); //这是不是警报(结果);
    }
    );

  });
 

解决方案

按照文档

  

在$阿贾克斯()函数返回XMLHtt prequest对象,它创建的。

这是你成功的回调函数返回的任何返回值被忽略。

您需要把价值在更广阔的范围内定义比回调函数(全局或pferably $ P $的外部函数中)内的变量。

 变种的结果;
   $阿贾克斯({
       ....
       成功:功能(数据){
          ...
          结果= ...;
       }
   });
 

或者更好的是:做你想要做的成功的回调函数中的返回值,这将让Ajax调用的异步特性,并意味着你不需要等待调用回来<。 / P>

做你处理的成功回调函数意味着你知道你的结果,如果你把该值的变量可能不是由时间来分配一个值,但一个变量,你要使用它。

在评论这一页你说的另外一个答案:

  

不过我打电话从其他多个功能runAjax功能不只是一个在我的code上面的例子,所以我需要返回的值,而不是runAjax功能做HTML代替

我想补充一个额外的参数,以你的runAjax功能,这是你可以在不同的处理功能,通过从不同的功能的另一回调函数。

 函数runAjax(data_obj,回调){
    $阿贾克斯({
        ...
        成功:功能(数据){
            ...
            结果= ...
            ...
            如果(typeof运算(回调)==功能){
                回调(结果);
            }
        }
    });
}
 

然后,你可以这样调用它

  runAjax({方法:method_set,ID:id_set},
    功能(结果){
         警报(结果);
    }
);
 

然后,你可以做的成功的功能数据的通用加工,但加工定制在回调函数每次调用。

如果你真的需要等待的呼叫,你可以通过异步选项创建同步AJAX调用:

  $。阿贾克斯({
    异步:假的,
    ....
 

I have a function runAjax that functions correctly. Unfortunately I am struggling to return the value I get from the ajax query.

The ajax function assigns the returned value inside "contents" or "error" xml tags to the variable "result".

If I alert the result variable inside the ajax function it alerts the correct value (i.e if the xml value inside contents is "published" it alerts published).

However if I alert the returned value from the runAjax function it alerts an object instead of the value of the internal variable "result" which in the above example is "published".

function runAjax (data_obj){
  return $.ajax({
      url:"/ajax.php",
      dataType: "xml",
      data: data_obj,
      success: function(data) {
        // format result
        var xml;
        if (typeof data == "string") {
          xml = new ActiveXObject("Microsoft.XMLDOM");
          xml.async = false;
          xml.loadXML(data);
        } else {
          xml = data;
        }
        var result;
        if($("error",xml).text()){
          result = [$("error",xml).text()];
        } else{
          result = [
            $("contents", xml).text()
          ];
        }
      alert(result); //alerts the correct string for example "published"
      return result;
      }
    });
  }
  $('ul.content li span.changeable').click(function(e){
    e.preventDefault();
    var method_set = $(this).parent().attr("class");
    var id_set = $(this).parent().parent().find('li.id span').html();
    var user = $(this);
    var result = runAjax({method: method_set, id: id_set});
    alert(result); //alerts an object not published

  });

Im sure it has something to do with the way I am returning the variable but I can't figure it out. Any input would be much appreciated.

Regards Luke

UPDATE: This is the revised code that works thanks to all the input from people below:

  function runAjax (data_obj,callback){
    $.ajax({
      url:"/ajax.php",
      dataType: "xml",
      data: data_obj,
      success: function(data) {
        // format result
        var xml;
        if (typeof data == "string") {
          xml = new ActiveXObject("Microsoft.XMLDOM");
          xml.async = false;
          xml.loadXML(data);
        } else {
          xml = data;
        }
        var result;
        if($("error",xml).text()){
          result = [$("error",xml).text()];
        } else{
          result = [
          $("contents", xml).text()
          ];
        }
        if ( typeof(callback) == "function") {
          callback(result);
        }
      }
    });
  }
  $('ul.content li span.changeable').click(function(e){
    e.preventDefault();
    var method_set = $(this).parent().attr("class");
    var id_set = $(this).parent().parent().find('li.id span').html();
    var user = $(this);
    runAjax({
      method: method_set, 
      id: id_set
    },
    function(result){
      $(user).html(result.join('')); //this is instead of alert(result);
    }
    );

  });

解决方案

According to the docs

The $.ajax() function returns the XMLHttpRequest object that it creates.

Any return value that you return from the success callback function is ignored.

You need to put the value in a variable defined in a wider scope than inside the callback function (global, or preferably inside an outer function).

   var result;
   $.ajax({
       ....
       success : function(data) {
          ...
          result = ...;
       }
   });

Or better yet: do whatever you want to do with the return value inside the success callback function, this will keep the asynchronous nature of the ajax call and means you don't need to wait for the call to come back.

Doing your processing in the success callback function means you know you have the results, if you put the value in a variable the variable may not be assigned a value yet by the time you want to use it.

In a comment to another answer on this page you say:

however I am calling the runAjax function from multiple other functions not just the one in my code example above, so I need the value returned rather than the runAjax function doing the html replacing

I would add an extra parameter to your runAjax function, which is another callback function that you can pass in different processing functions from the various functions.

function runAjax(data_obj, callback) {
    $.ajax({
        ...
        success : function(data) { 
            ...
            result = ...
            ...
            if ( typeof(callback) == "function") {
                callback(result);
            }
        }
    });
}

Then you can call it like

runAjax({method: method_set, id: id_set},
    function(result){
         alert(result);
    }
);

Then you can do your generic processing of the data in the success function, but the custom processing for each call in the callback function.

If you really need to wait for the call, you can create a synchronous ajax call by passing the async option:

 $.ajax({
    async:false,
    ....

这篇关于JQuery的AJAX功能工作,但不能正确地返回变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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