Jquery Javascript Variable

Jquery Javascript Variable

本文关键字:Variable Javascript Jquery      更新时间:2023-09-26

你好,我已经搜索了整个网站的解决方案,发现了一些东西,但没有得到它的工作。

-在页面的头部区域有main函数。(这将从PHP返回数据)

-这个数据我需要作为一个变量,但不知道如何处理。

function note(content,usern){
note = Function("");
  $.ajax({
   type: "POST",
   url: "note.php",
   data: {'token': content, 'user': usern },   success: function(data){ var myneededvar = data;  },    });  }

好的,这是有效的,也给出了数据现在我在脚本中像这样调用函数

 note(token,notename);

and I need the result myneeddedvar

首先,您的变量myneededvar是成功处理程序函数的本地变量,在外部不可用。

其次,您的AJAX调用是异步的,您不能期望在AJAX调用语句之后立即在变量中获得AJAX返回数据。

。,你不能做:

note(...); // call your method
alert(myneededvar); // this won't work as the AJAX call wouldn't have completed

第三,不确定为什么这里有note = Function("");语句。你应该把它去掉。

应该这样做:

var myneededvar;
function note(content, usern){
    $.ajax({
        type: "POST",
        url: "note.php",
        data: {'token': content, 'user': usern },
        success: function(data){
            myneededvar = data;
            // use it here or call a method that uses myneededvar
        }
    });
}