问题描述
如果你在函数/作用域之外声明了一个变量,并且然后它改变之前声明的变量......对吗?然而,第一个警报返回正确的价格,但第二个(()
//得到定价
var price = 0;
var modelid = $(#model_input)。val();
var inCode = $(#code_input)。val();
$ .get(getpricing.php,{'modelid':modelid,'code':inCode},函数(data){
price = data;
alert(price);
});
alert(price);
您正在使用 A jax请求。
那些指定的否则是 A 同步:它们在后台执行,不停止执行其余的。
因此,最后一行代码中的 alert
在Ajax请求完成之前执行;这意味着当时 price
仍然为0。
改变这种情况的一种方法是使用同步请求(请参阅);但我强烈建议不要这样做;引用该文档:
你肯定不希望你的应用程序冻结整个浏览器!
你应该重新考虑应用程序的设计方式,在这种情况下:只有在完成Ajax请求后才能使用价格信息 - 这可能意味着您应该在调用成功的函数中放置更多代码:将代码放在 $之后。得到
是不够的。
I thought I had this mess sorted out in my head but for some odd reason its not working.
If you declare a variable outside of a function / scope and refer to it without the var inside a function then it changes the variable declared previously... right?
however, the first alert returns the correct price, but the second (last) alert returns 0. What am I doing wrong?
//get pricing
var price=0;
var modelid = $("#model_input").val();
var inCode = $("#code_input").val();
$.get("getpricing.php", { 'modelid': modelid ,'code' : inCode }, function(data){
price = data;
alert(price);
});
alert(price);
You are using an Ajax request.
Those, unkess specified otherwise, are Asynchrounous : they are executed in the background, without stopping the execution of the rest of the script.
So, the alert
on the last line of code is executed before the Ajax request is finished ; which means price
is still 0 at that time.
One way to change that would be to use a synchronous request (see async option) ; but I strongly advise against it ; quoting the doc :
And you definitly don't want your application to freeze the whole browser!
You should re-think the way your application is designed, in this case : you can only use the "price" information after the Ajax request is finished -- which probably means you should place more code inside the function called on its success : just placing code after the $.get
is not enough.
这篇关于Javascript本地与全球的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!