简体   繁体   English

javascript ajax在浏览器控制台中返回值“被盗”

[英]javascript ajax returned value “stolen” in browser console

I've got following javascript code that I execute in the browser: 我有以下在浏览器中执行的javascript代码:

function run(request) {
    var res;
    $.ajax({
      url:'http://custom-host:8080/',
      type: "POST",
      async: false,
      data: request
    }).done(function(data, textStatus, jqXHR){
      console.log(textStatus);
      res = data;
    });
    return res;
}

It just asks my custom server for a response that it gets. 它只是要求我的自定义服务器获得响应。 The Chrome Console log looks like this: Chrome控制台日志如下所示:

> var a = run({command:'version'}); // executing custom function
success dev.pycached-admin/:14 // this is the console log
undefined // this is the console returned value
> a // ask for value a
"1.1" // value a (returned from ajax)

The question is: how come undefined is returned in the console, when actual value of '1.1' is returned afterwards (the value is correctly assigned)? 问题是:当随后返回“ 1.1”的实际值(正确分配值)时,在控制台中如何返回undefined?

If I add debugger statement inside the done function: 如果我在完成的函数中添加debugger语句:

}).done(function(data, textStatus, jqXHR){
  console.log(textStatus);
  debugger;
  res = data;
});

then I can see Apple's code which probably maintains the chrome console ( VM files in the script tab). 然后我可以看到Apple的代码,该代码可能维护chrome控制台(脚本选项卡中的VM文件)。 Anyway, the AJAX call is synchronous, so why is the value not returned for the first time? 无论如何,AJAX调用是同步的,那么为什么第一次没有返回该值?

...so why is the value not returned for the first time? ...那么为什么第一次不返回该值?

It is, but var is a statement, not an expression, and so it cannot have a result for the console to display. 它是,但是var是一个语句,而不是表达式,因此控制台无法显示结果。 You can see this if you just do this: 您只需执行以下操作即可看到:

> var a = "foo";
undefined
> a
"foo"

So just do this: 因此,只需执行以下操作:

> var a
undefined
> a = run({command:'version'});

...which should give you: ...应该给您:

success dev.pycached-admin/:14 // this is the console log
"1.1"

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

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