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 :
By default, all requests are sent
asynchronous (i.e. this is set to true
by default). If you need synchronous
requests, set this option to 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…