jQuery 使用javascript将函数返回值分配给某个变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3941381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
assign function return value to some variable using javascript
提问by Ra.
I have a js function , after doing some business logic, the javascript function should return some result to another variable.Sample code below
我有一个 js 函数,在做了一些业务逻辑之后,javascript 函数应该将一些结果返回给另一个变量。下面的示例代码
var response="";
function doSomething() {
$.ajax({
url:'action.php',
type: "POST",
data: dataString,
success: function (txtBack) {
if(txtBack==1) {
status=1;
}
});
return status;
}
Here i want to use like
在这里我想使用像
response=doSomething();
I want to assign a return value "status" "var response".But the result is 'undefined'.
我想分配一个返回值“状态”“var 响应”。但结果是“未定义”。
回答by ?ime Vidas
Or just...
要不就...
var response = (function() {
var a;
// calculate a
return a;
})();
In this case, the response variable receives the return value of the function. The function executes immediately.
在这种情况下,响应变量接收函数的返回值。该函数立即执行。
You can use this construct if you want to populate a variable with a value that needs to be calculated. Note that all calculation happens inside the anonymous function, so you don't pollute the global namespace.
如果要使用需要计算的值填充变量,则可以使用此构造。请注意,所有计算都在匿名函数内部进行,因此您不会污染全局命名空间。
回答by Matt
AJAX requests are asynchronous. Your doSomething function is being exectued, the AJAX request is being made but it happens asynchronously; so the remainder of doSomething is executed and the value of status
is undefined when it is returned.
AJAX 请求是异步的。您正在执行 doSomething 函数,正在发出 AJAX 请求,但它是异步发生的;所以 doSomething 的其余部分被执行,status
返回时的值是未定义的。
Effectively, your code works as follows:
实际上,您的代码按如下方式工作:
function doSomething(someargums) {
return status;
}
var response = doSomething();
And then some time later, your AJAX request is completing; but it's already too late
然后一段时间后,你的 AJAX 请求完成了;但已经太晚了
You need to alter your code, and populate the "response" variable in the "success" callback of your AJAX request. You're going to have to delay using the response until the AJAX call has completed.
您需要更改代码,并在 AJAX 请求的“成功”回调中填充“响应”变量。您将不得不延迟使用响应,直到 AJAX 调用完成。
Where you previously may have had
你以前可能有过的地方
var response = doSomething();
alert(response);
You should do:
你应该做:
function doSomething() {
$.ajax({
url:'action.php',
type: "POST",
data: dataString,
success: function (txtBack) {
alert(txtBack);
})
});
};
回答by Darin Dimitrov
You could simply return a value from the function:
您可以简单地从函数返回一个值:
var response = 0;
function doSomething() {
// some code
return 10;
}
response = doSomething();
回答by impulsgraw
The only way to retrieve the correct value in your context is to run $.ajax()
function synchronously (what actually contradicts to main AJAX idea). There is the special configuration attribute async
you should set to false
. In that case the main scope which actually contains $.ajax()
function call is paused until the synchronous function is done, so, the return
is called only after $.ajax()
.
在上下文中检索正确值的唯一方法是$.ajax()
同步运行函数(这实际上与主要的 AJAX 思想相矛盾)。async
您应该将特殊配置属性设置为false
。在这种情况下,实际包含$.ajax()
函数调用的主作用域会暂停,直到同步函数完成,因此,return
仅在$.ajax()
.
function doSomething() {
var status = 0;
$.ajax({
url: 'action.php',
type: 'POST',
data: dataString,
async: false,
success: function (txtBack) {
if (txtBack == 1)
status = 1;
}
});
return status;
}
var response = doSomething();
回答by Aley
The result is undefined
since $.ajax
runs an asynchronous operation. Meaning that return status
gets executed before the $.ajax
operation finishes with the request.
结果是undefined
因为$.ajax
运行了一个异步操作。意思是return status
在$.ajax
操作完成请求之前执行。
You may use Promiseto have a syntax which feels synchronous.
您可以使用Promise来获得感觉同步的语法。
function doSomething() {
return new Promise((resolve, reject) => {
$.ajax({
url:'action.php',
type: "POST",
data: dataString,
success: function (txtBack) {
if(txtBack==1) {
resolve(1);
} else {
resolve(0);
}
},
error: function (jqXHR, textStatus, errorThrown) {
reject(textStatus);
}
});
});
}
You can call the promise like this
你可以这样调用promise
doSomething.then(function (result) {
console.log(result);
}).catch(function (error) {
console.error(error);
});
or this
或这个
(async () => {
try {
let result = await doSomething();
console.log(result);
} catch (error) {
console.error(error);
}
})();