其他函数无法使用 $.get 中的 jQuery 数据
大家好,我有这段代码,但它总是抛出“未定义;”
var projectID = $.getUrlVar('id');
var projectname;
$.get('functions.php?func=projectname&id='+projectID, function(data) {
projectname = data;
alert(projectname+'<- see nice content');
});
alert(projectname+'<- no content :(');
我怎样才能使“projectname”在该 get 函数之外可用?
(我确实注意到,当实际运行该代码时,在好的内容之前弹出了无内容警报。.get 是运行页面上的最后一件事吗?这就是为什么它全是空白的吗?因为变量似乎不是设置了吗?
谢谢
hi all i've got this bit of code but it keeps kicking out 'undefined;
var projectID = $.getUrlVar('id');
var projectname;
$.get('functions.php?func=projectname&id='+projectID, function(data) {
projectname = data;
alert(projectname+'<- see nice content');
});
alert(projectname+'<- no content :(');
how can i make "projectname" available outside that one get function?
(i did notice, when running that code actually, that the no content alert popped up before the nice content. is the .get the last thing on the page that runs? is this why its all blank? coz the variable doesnt appear to be set yet?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
AJAX 异步运行(这就是
AJAX
首字母缩略词中的第一个A
的含义)。因此,您的问题有两种解决方案:
$.get
更改为$.ajax
并将其async
选项设置为 false (糟糕的解决方案)AJAX runs asynchronously (that is what first
A
inAJAX
acronym stands for).So you have 2 solutions for your issue:
$.get
to$.ajax
and set itsasync
option to false (terrible solution)这里的问题是您的第二个警报实际上在 AJAX 请求完成之前执行。
“AJAX”中的“A”代表异步。
任何依赖于 AJAX 请求返回的数据的功能都只能在
success
回调中实现或由其调用The problem here is that your second alert actually executes before the AJAX request has finished.
The "A" in "AJAX" stands for Asynchronous.
Any functionality relying on data returned from an AJAX request should only be implemented within or called by the
success
callback因为 XHR 是异步的,所以你不能喜欢这样。
将所有代码作为后代函数处理,位于调用堆栈的更深处,源自完整的回调(其中
projectname
将分配正确的值)。Because the XHR is asynchronous, you can't like that.
Handle all code as a descendent function, deeper on the callstack with an origination from the complete callback (where
projectname
will have the correct value assigned).