Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/420.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/89.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript函数中未定义的变量_Javascript_Jquery_Ajax_Undefined - Fatal编程技术网

JavaScript函数中未定义的变量

JavaScript函数中未定义的变量,javascript,jquery,ajax,undefined,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函数中

我在一个按钮点击函数中有以下代码

var ItemID2;

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

console.log(ItemID2);
单击按钮后,我在控制台中看到
ItemID2
未定义。如果在get函数中使用
console.log(数据[0].ItemID)
,我会看到正确的值。我认为问题在于函数的执行仍在继续,但Ajax尚未检索
ItemID2
的值。你知道我该怎么解决吗

我认为问题在于函数的执行仍在继续,但Ajax尚未检索ItemID2的值


没错,这是一个异步函数。您必须将程序流恢复到请求的回调。

A-JAX是A-同步的

这就是为什么有回调函数。

简单:

var ItemID2;

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

AJAX第一个“A”是什么意思?AJAX是异步的。您可以修复它,但我建议改为围绕它进行编码。修复它意味着使浏览器看起来损坏。
console.log
在ajax调用完成之前执行。@adeneo thx对于粗体,我们可以将其作为重复项关闭吗?这个问题一天要问30次。说真的,当这个问题出现时,不要投票,不要评论,不要回答。投你一票就行了。