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次。说真的,当这个问题出现时,不要投票,不要评论,不要回答。投你一票就行了。