简体   繁体   English

Javascript Local vs Global

[英]Javascript Local vs Global

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? 如果在函数/作用域之外声明一个变量并在函数内部没有var的情况下引用它,那么它会改变先前声明的变量......对吗?

however, the first alert returns the correct price, but the second (last) alert returns 0. What am I doing wrong? 但是,第一个警报返回正确的价格,但第二个(最后一个)警报返回0.我做错了什么?

//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 A jax request. 您正在使用A jax请求。

Those, unkess specified otherwise, are A synchrounous : they are executed in the background, without stopping the execution of the rest of the script. 那些未指定 unkess是A同步的:它们在后台执行,而不会停止执行脚本的其余部分。

So, the alert on the last line of code is executed before the Ajax request is finished ; 因此,在Ajax请求完成之前执行最后一行代码的alert ; which means price is still 0 at that time. 这意味着当时price仍为0。

One way to change that would be to use a synchronous request (see async option ) ; 改变的一种方法是使用同步请求(参见async选项 ); but I strongly advise against it ; 但我强烈建议不要这样做; quoting the doc : 引用文档:

By default, all requests are sent asynchronous (ie this is set to true by default). 默认情况下,所有请求都是异步发送的(默认情况下设置为true)。 If you need synchronous requests, set this option to false. 如果需要同步请求,请将此选项设置为false。 Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. 请注意,同步请求可能会暂时锁定浏览器,并在请求处于活动状态时禁用任何操作。

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. 您应该重新考虑应用程序的设计方式,在这种情况下:您只能在Ajax请求完成后使用“价格”信息 - 这可能意味着您应该在成功调用函数中放置更多代码:just在$.get之后放置代码是不够的。

使用.get的httprequests是异步的,因此第一个警报(第二个声明的警报)将警告原始值,因为请求的回调尚未触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM