简体   繁体   English

设置jQuery $ .post将数据返回到JavaScript变量

[英]Setting the jQuery $.post return data to a JavaScript variable

I have the following jQuery code in my HTML page: 我的HTML页面中有以下jQuery代码:

$.post("MyPHP.php", {category: CATEGORY}, function(data){var test = data;});

But I can't seem to use test anywhere else in my page. 但我似乎无法在我的页面中的任何其他地方使用测试。 I know this is AJAX so I have to wait for $.post to complete but the variable test is never set. 我知道这是AJAX所以我必须等待$.post完成,但变量测试从未设置。 If I instead use the return data to change the innerhtml of a paragraph, the paragraph updates after a small delay. 如果我改为使用返回数据来更改段落的innerhtml,则段落会在一小段延迟后更新。

Any thoughts? 有什么想法吗?

EDIT: Cracked it! 编辑:破解它! You can call another function from the $.post return function, ie: function(data){setVar(data)}); 您可以从$.post返回函数调用另一个函数,即: function(data){setVar(data)}); and simply define the setVar(data) function as follows: 并简单地定义setVar(data)函数,如下所示:

function setVar(data){test = data;}

Provided test has already been defined in global scope var test; 已提供测试已在全局范围var test;定义var test; you can use it through out the rest of your code. 您可以在其余代码中使用它。

because the scope of your var is limited try moving your test variable to a much global scope 因为var的范围有限,请尝试将测试变量移动到更全局的范围

 var test; $.post("MyPHP.php", {category: CATEGORY}, function(data){ test = data; }); 

ajax requests are asynchronous so you will never know when it is complete unless you put your variable in the success callback (which) you did or you can make the ajax request synchronous (plz dont do that) or you can use .when to make sure that your ajax call dependent code is executed when all the variables are set. ajax请求是异步的,所以你永远不知道它什么时候完成,除非你把你的变量放在你做的成功回调(你)或你可以使ajax请求同步(plz不要这样做)或你可以使用.when确保在设置所有变量时执行ajax调用依赖代码。

see this demo even if you move the test variable to the global scope it still logs undefined to the console so try 即使您将测试变量移动到全局范围,它仍会将undefined的日志记录到控制台,请参阅此演示

var test;
var x=$.post("MyPHP.php", {category: CATEGORY},, function(data){  
    test = data;   
});
console.log(test);// still undefined    
$.when( x ).then(function(args){
     console.log(test);// your var is set
});

http://jsfiddle.net/C4JnU/1/ http://jsfiddle.net/C4JnU/1/

You have declared your test variable within the ajax success function, therefore its scope is limited to the success function. 您已在ajax成功函数中声明了您的test变量,因此其范围仅限于成功函数。 If you want to access it from other code you can declare it in the global scope, and just overwrite it in the success function. 如果要从其他代码访问它,可以在全局范围内声明它,只需在success函数中覆盖它。

var test; // delcared in global scope

$.post("MyPHP.php", {category: CATEGORY}, function(data){ test = data;});

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

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