JavaScript函数中的未定义变量

时间:2013-05-03 17:30:49

标签: javascript jquery ajax undefined

我在按钮单击功能

中有以下代码
var ItemID2;

$.get("http://localhost/tddd27/index.php/json/Products?ItemName="+thisID, 
          function(data){
             ItemID2=data[0].ItemID;
            },"json");

console.log(ItemID2);

单击我在控制台中看到的ItemID2未定义的按钮。如果我在get-function中使用console.log(data[0].ItemID),我会看到正确的值。我认为问题在于函数的执行仍在继续,但Ajax尚未检索ItemID2的值。我知道如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

  

我认为问题在于函数的执行仍在继续,但Ajax还没有检索ItemID2的值。

你是对的,它是一个异步功能。您必须将程序流程恢复到请求的回调。

答案 1 :(得分:2)

A -JAX A - 同步。

这就是回调函数的原因。

答案 2 :(得分:2)

简单:

var ItemID2;

$.get("http://localhost/tddd27/index.php/json/Products?ItemName="+thisID, 
          function(data){
             ItemID2=data[0].ItemID;
             console.log(ItemID2);
            },"json");