Ajax成功函数无法在jquery mobile中运行

时间:2021-01-05 21:29:28

I am trying to validate a basic login form with username and password fields. I need to validate username and password from check.php ajax page. There is no problem in ajax request and response. I am getting proper response from ajax page. But Ajax success function is not working properly.

我正在尝试使用用户名和密码字段验证基本登录表单。我需要从check.php ajax页面验证用户名和密码。 ajax请求和响应没有问题。我从ajax页面得到了适当的回应。但是Ajax的成功功能不能正常工作。

ajaxrequest.html

ajaxrequest.html

$(document).on('pagebeforeshow', '#login', function(){
        $(document).on('click', '#submit', function() {
        if($('#username').val().length > 0 && $('#password').val().length > 0){
                $.ajax({
                    url : 'serverurl/check.php',
                    data: {action : 'login', formData : $('#check-user').serialize()},
                    type: 'post',                   
                    beforeSend: function() {
                        $.mobile.loading(true);
                        alert("beforesend");
                    },
                    complete: function() {
                        $.mobile.loading(false);
                        alert("complete");
                    },
                    success: function (result) {
                        console.log("Ajax response");   
                        res = JSON.stringify(result);
                        if(res.status == "success"){    
                        resultObject.formSubmitionResult = res.uname;
                        localStorage["login_details"] = window.JSON.stringify(result);
                        $.mobile.changePage("#second");
                }else{
                        $.mobile.changePage("#login");
                        alert("incorrect login");           
                }
                    },
                    error: function (request,error) {
                        alert('Network error has occurred please try again!');
                    }
                });                   
        } else {
            alert('Fill all fields');
        }           
            return false;
        });    
});

Here i have added my ajax page. This page only validates posted username and password. Finally it returns json object. What am i doing wrong?

在这里,我添加了我的ajax页面。此页面仅验证发布的用户名和密码。最后它返回json对象。我究竟做错了什么?

serverurl/check.php

SERVERURL / check.php

header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
if(isset($_POST['formData']) && isset($_POST['action']) && $_POST['action'] == 'login'){
    parse_str($_POST['formData'],$searchArray);
    $uname = "arun";
    $pwd = "welcome";
    $resultArray = array();
    if($uname == $searchArray['username'] && $pwd == $searchArray['password'])      
    {
        $resultArray['uname'] = $searchArray['username'];
        $resultArray['pwd'] = $searchArray['password'];
        $resultArray['status'] = 'success';
    }else{
        $resultArray['status'] = 'failed';
    }
    echo json_encode($resultArray);
}

4 个解决方案

#1


1  

Your code should be

你的代码应该是

success: function (result) {
                        console.log("Ajax response");   
                        //don't do this
                        //res = JSON.stringify(result);
                        if(result.status == "success"){    
                        resultObject.formSubmitionResult = result.uname;
                        localStorage["login_details"] = window.JSON.stringify(result);
                        $.mobile.changePage("#second");
                }else{
                        $.mobile.changePage("#login");
                        alert("incorrect login");           
                }

After JSON.stringify you are accessing like stringJson.status this will not work. it mast have "parsed" "json object" not stringify.

在JSON.stringify之后你正在访问stringJson.status,这将无法正常工作。它的桅杆有“解析”“json对象”没有stringify。

#2


1  

Don't need to convert your JSON to String.

不需要将JSON转换为String。

$(document).on('pagebeforeshow', '#login', function(){
        $(document).on('click', '#submit', function() {
        if($('#username').val().length > 0 && $('#password').val().length > 0){
                $.ajax({
                    url : 'serverurl/check.php',
                    data: {action : 'login', formData : $('#check-user').serialize()},
                    type: 'post',                   
                    beforeSend: function() {
                        $.mobile.loading(true);
                        alert("beforesend");
                    },
                    complete: function() {
                        $.mobile.loading(false);
                        alert("complete");
                    },
                    success: function (result) {
                        console.log("Ajax response");   
                        //Don't need to converting JSON to String
                        //res = JSON.stringify(result);
                        //directly use result 
                        if(result.status == "success"){    
                        resultObject.formSubmitionResult = result.uname;
                        localStorage["login_details"] = window.JSON.stringify(result);
                        $.mobile.changePage("#second");
                }else{
                        $.mobile.changePage("#login");
                        alert("incorrect login");           
                }
                    },
                    error: function (request,error) {
                        alert('Network error has occurred please try again!');
                    }
                });                   
        } else {
            alert('Fill all fields');
        }           
            return false;
        });    
});

#3


1  

Your AJAX call is perfect but datatype is not declared in ajax

您的AJAX调用是完美的,但数据类型未在ajax中声明

Try with jSON OR JSONP. You will get success.

尝试使用jSON或JSONP。你会获得成功。

$.ajax({
    url : 'serverurl/check.php',                    
    type: 'post',
    dataType: "json", OR "jsonp",
    async: false,
    data: {action : 'login', formData : $('#check-user').serialize()},
        beforeSend: function() {
        $.mobile.loading(true);
        alert("beforesend");
    },
    complete: function() {
        $.mobile.loading(false);
        alert("complete");
    },
    success: function (result) {
        console.log("Ajax response");   
        alert(JSON.stringify(result)); // Check response in alert then parse according to that
        res = JSON.stringify(result);
        if(res.status == "success"){    
        resultObject.formSubmitionResult = res.uname;
        localStorage["login_details"] = window.JSON.stringify(result);
        $.mobile.changePage("#second");
}else{
        $.mobile.changePage("#login");
        alert("incorrect login");           
}
    },
    error: function (request,error) {
        alert('Network error has occurred please try again!');
    }
});  

#4


1  

Under some circumstances your server might not return the response correctly. Have you tried to handle the actual response code (e.g. if your server returns 200) like this:

在某些情况下,您的服务器可能无法正确返回响应。您是否尝试过处理实际响应代码(例如,如果您的服务器返回200),如下所示:

 $.ajax({
         url : 'serverurl/check.php',
         data: {action : 'login', formData : $('#check-user').serialize()},
         type: 'post', 
         .... 
         statusCode: {
               200: function (response) {
                      // do your stuff here
                    }
         }
 });

#1


1  

Your code should be

你的代码应该是

success: function (result) {
                        console.log("Ajax response");   
                        //don't do this
                        //res = JSON.stringify(result);
                        if(result.status == "success"){    
                        resultObject.formSubmitionResult = result.uname;
                        localStorage["login_details"] = window.JSON.stringify(result);
                        $.mobile.changePage("#second");
                }else{
                        $.mobile.changePage("#login");
                        alert("incorrect login");           
                }

After JSON.stringify you are accessing like stringJson.status this will not work. it mast have "parsed" "json object" not stringify.

在JSON.stringify之后你正在访问stringJson.status,这将无法正常工作。它的桅杆有“解析”“json对象”没有stringify。

#2


1  

Don't need to convert your JSON to String.

不需要将JSON转换为String。

$(document).on('pagebeforeshow', '#login', function(){
        $(document).on('click', '#submit', function() {
        if($('#username').val().length > 0 && $('#password').val().length > 0){
                $.ajax({
                    url : 'serverurl/check.php',
                    data: {action : 'login', formData : $('#check-user').serialize()},
                    type: 'post',                   
                    beforeSend: function() {
                        $.mobile.loading(true);
                        alert("beforesend");
                    },
                    complete: function() {
                        $.mobile.loading(false);
                        alert("complete");
                    },
                    success: function (result) {
                        console.log("Ajax response");   
                        //Don't need to converting JSON to String
                        //res = JSON.stringify(result);
                        //directly use result 
                        if(result.status == "success"){    
                        resultObject.formSubmitionResult = result.uname;
                        localStorage["login_details"] = window.JSON.stringify(result);
                        $.mobile.changePage("#second");
                }else{
                        $.mobile.changePage("#login");
                        alert("incorrect login");           
                }
                    },
                    error: function (request,error) {
                        alert('Network error has occurred please try again!');
                    }
                });                   
        } else {
            alert('Fill all fields');
        }           
            return false;
        });    
});

#3


1  

Your AJAX call is perfect but datatype is not declared in ajax

您的AJAX调用是完美的,但数据类型未在ajax中声明

Try with jSON OR JSONP. You will get success.

尝试使用jSON或JSONP。你会获得成功。

$.ajax({
    url : 'serverurl/check.php',                    
    type: 'post',
    dataType: "json", OR "jsonp",
    async: false,
    data: {action : 'login', formData : $('#check-user').serialize()},
        beforeSend: function() {
        $.mobile.loading(true);
        alert("beforesend");
    },
    complete: function() {
        $.mobile.loading(false);
        alert("complete");
    },
    success: function (result) {
        console.log("Ajax response");   
        alert(JSON.stringify(result)); // Check response in alert then parse according to that
        res = JSON.stringify(result);
        if(res.status == "success"){    
        resultObject.formSubmitionResult = res.uname;
        localStorage["login_details"] = window.JSON.stringify(result);
        $.mobile.changePage("#second");
}else{
        $.mobile.changePage("#login");
        alert("incorrect login");           
}
    },
    error: function (request,error) {
        alert('Network error has occurred please try again!');
    }
});  

#4


1  

Under some circumstances your server might not return the response correctly. Have you tried to handle the actual response code (e.g. if your server returns 200) like this:

在某些情况下,您的服务器可能无法正确返回响应。您是否尝试过处理实际响应代码(例如,如果您的服务器返回200),如下所示:

 $.ajax({
         url : 'serverurl/check.php',
         data: {action : 'login', formData : $('#check-user').serialize()},
         type: 'post', 
         .... 
         statusCode: {
               200: function (response) {
                      // do your stuff here
                    }
         }
 });