在函数jquery ajax调用中调用变量并返回undefined

时间:2014-05-27 12:03:06

标签: jquery ajax function variables

我是关于jquery和ajax的新手,我想问一下我的代码。我为我的应用程序创建了一个表单,当我提交表单时,它将更改页面并从ajax进程获取“id_login”。

我的问题是我无法调用我在$ .ajax中分配的变量,并且在我更改页面后它将显示在“#info”上。但它显示的是undefiend而不是值。我不知道它的问题在哪里,我的代码如下:

var getVar;    
$('#submit').click(function(){
            var u= $("#username").val();
            var p= $("#password").val();
            if (u !="" && p !==""){

                $.ajax({
                type : 'POST',
                url : 'test.php',
                beforeSend: function(x) {
                    if(x && x.overrideMimeType) {
                        x.overrideMimeType("application/j-son;charset=UTF-8");
                    }
                },
                data:{username:u,password:p},
                async:false,
                global:false,
                dataType:"json",
                success: function(data){
                    if (data.success == true){
                        window.localStorage.setItem("id_login",data.session);
                        getVar = window.localStorage.getItem("id_login");//the value is 1
                        $.mobile.changePage('#page1');
                    }
                }

                }); 

            }

        });

            $("#info").append("result:"+getVar);//the result always show undefiend not 1

我一直在寻找解决我的问题在互联网包括全局变量,调用函数内部等等。但它仍然无效。 所以,有人可以告诉我这个问题吗? 对不起,如果我的英语不好 谢谢

1 个答案:

答案 0 :(得分:0)

success: function(data){
                if (data.success == true){
                    window.localStorage.setItem("id_login",data.session);
                    getVar = window.localStorage.getItem("id_login");//the value is 1

                    $("#info").append("result:"+getVar);
                    //this has to run every time you get a 
                    //successful Ajax call and you want
                    //this variable to be printed out correct.
                    $.mobile.changePage('#page1');

                }