为什么不能从Jquery $ .post函数(JavaScript)内部更改值 [英] Why can't change the value from inside Jquery $.post function (JavaScript)

查看:61
本文介绍了为什么不能从Jquery $ .post函数(JavaScript)内部更改值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从ajax调用获取响应并将其保存为另一个值,但将无法正常工作 这是我的代码

I am trying to get the response from ajax call and save it in another value but wont work this is my code

x='go'
$.post("someurl",function(data){
    x=data;
})
alert(x)//go

或这个 jsFiddle

我正在寻找一种解决此问题的方法,而不将值存储在任何HTML容器中

I am looking for a solution for this problem without storing the value in any HTML container

推荐答案

$.post是异步的-回调将稍后在alert(x)行之后的 之后执行.

$.post is asynchronous - the callback will be executed later, after your alert(x) line.

尝试:

$.post("someurl",function(data){
    x=data;
    alert(x)
})

(不,没有其他办法-您必须相应地重组代码.不要试图将async设置为false,否则最终会遇到更大的问题).

(No, there's no other way around this - you'll have to restructure your code accordingly. Don't be tempted to try setting async to false, or you'll end up with bigger problems).

这篇关于为什么不能从Jquery $ .post函数(JavaScript)内部更改值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆