jQuery函数ajax函数内部的全局变量有问题 [英] jquery having issue with global variable inside function ajax function

查看:85
本文介绍了jQuery函数ajax函数内部的全局变量有问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是代码:

var ret;
function fetch_data(param1){
  $.post(param1,
        function(data){
          if (data){
            ret = data*2;
            console.log("data", ret);
          }
          else{
            ret = 15;
            console.log("no data")
          }
        });
  return ret;
}

function hello(){
  ret = fetch_data("/post_data");
  console.log("from the main function", ret);
}

以上是我如何处理事物的简化架构. 我向url发出发布请求,并尝试根据返回的值获取值.我操纵该值,然后尝试将其返回给函数. console.log显示fetch_data函数内部的值,而不显示hello函数内部的值.表示不返回任何值.我在哪里弄错了?

The above is a simplified schema of how i am working with things. i make a post request to a url and try to get the value, based on the returned value i manipulate the value and try returning it back to the function. The console.log shows a value inside the fetch_data function, but not within the hello function. Meaning no value is returned. Where am i getting it wrong?

推荐答案

在您的javascript进行初始ajax调用之后,脚本的执行将继续执行return语句.此时,尚未返回对您请求的响应,因此尚未执行您的回调函数,这意味着尚未为ret分配值.您需要在回调函数中包含对hello的调用,以确保为ret分配了一个值.

After your javascript makes the initial ajax call the execution of the script proceeds to the return statement. At this point the response to your request has not been returned yet, therefore your callback function has not executed, meaning ret has not been assigned a value. You need to include the call to hello within your callback function in order to guarantee that ret has been assigned a value.

  var ret;
    function fetch_data(param1){
      $.post(param1,
            function(data){
              if (data){
                ret = data*2;
                console.log("data", ret);
              }
              else{
                ret = 15;
                console.log("no data")
              }
              hello();
            });
    }

function hello(){
  ret = fetch_data("/post_data");
  console.log("from the main function", ret);
}

Ajax可以通过两种方式访问​​服务器.它们是同步的(在脚本停止之前等待脚本发送并等待服务器发送回继续,然后继续)和异步的(在脚本允许页面继续处理并在到达时以及到达时处理答复).您的函数正在异步执行,这意味着fetch_data函数正在ajax调用完成之前执行return语句.

There are two ways that Ajax can access the server. These are synchronous (wnere the script stops and waits for the server to send back a reply before continuing) and asynchronous (where the script allows the page to continue to be processed and will handle the reply if and when it arrives). Your function is performing asynchromnously, meaning the fetch_data function is executing the return statement before the ajax call is completed.

事件顺序:

  1. fetch_data被称为
  2. fetch_data触发ajax请求.
  3. 获取数据将返回ret(未定义)
  4. hello函数将ret打印到控制台
  5. 从服务器收到
  6. ajax响应
  7. ret基于ajax响应分配了一个值
  1. fetch_data is called
  2. fetch_data fires off ajax request.
  3. fetch data returns ret(undefined)
  4. hello function prints ret to console
  5. ajax response is received from server
  6. ret is assigned a value based upon ajax response

我想进一步建议您将代码修改为我认为是更好的方法.我相信这种方法比在回调中指定hello函数更好地捕获了您的意图.

I would like to further suggest that you modify your code to what I consider to be a better approach. I believe this approach captures your intent better than specifying the hello function within your callback.

    function fetch_data(param1,callback){
      $.post(param1,
            function(data){
              callback(data);
            });
    }

function hello(data){
    if (data){
       ret = data*2;
       console.log("data", ret);
     }
     else{
       ret = 15;
       console.log("no data")
     }
  console.log("from the main function", ret);
}

function hello2(data){
  //...different logic that modifies data
  console.log("from the main function", ret);
}

//Function call passing the hello function as a parameter
fetch_data('/post_data', hello);

//Function call that passes hello2 function as a parameter
fetch_data('/post_data', hello2);

这篇关于jQuery函数ajax函数内部的全局变量有问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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