[英]Variable not working as expected JQuery
I have a function: 我有一个功能:
function name(type)
{
$.i="";
$.post("name.php", type, function(data, status){
$(".pic").attr("src", data);
$.i=data;
})
alert($.i); //this is not working
}
In the above code the alert is displaying empty alert box. 在上面的代码中,警报显示为空警报框。 But when i have 但是当我有
function name(type)
{
$.i="";
$.post("name.php", type, function(data, status){
$(".pic").attr("src", data);
$.i=data;
alert($.i); //now this is working
})
}
I want to return the value returned by name.php file . 我想返回name.php文件返回的值。 name.php
contains echo "string"
. name.php
包含echo "string"
。 It is for testing only. 仅用于测试。 In the second given code string
is displaying but in first it is not working. 在第二个给定的代码string
中显示,但在第一个它不起作用。
What can i do to return the value from the function and assign the received value to variable declared outside $.post() or in the function. 我该怎么做才能从函数返回值并将接收到的值分配给在$ .post()外部或函数中声明的变量。
Thanks in advance. 提前致谢。
The async call back of post is call after the execution of post. post的异步回调是post执行后的调用。 You can call a function from post to perform operation on value return in callback. 您可以从post调用函数以对回调中的值返回执行操作。
function name(type)
{
$.i="";
$.post("name.php", type, function(data, status){
$(".pic").attr("src", data);
$.i=data;
//alert($.i); //now this is working
callToFunctionPassingData(data);
})
}
You can try using deffered execution this post will guid you how to achieve it. 您可以尝试使用延迟执行,这篇文章将指导您如何实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.