Ajax成功函数在jquery mobile中不起作用

Ajax success function not working in jquery mobile

本文关键字:mobile 不起作用 jquery 成功 函数 Ajax      更新时间:2023-09-26

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

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;
        });    
});

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

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);
}

您的代码应该是

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");           
                }

JSON.stringify之后,您像stringJson.status一样访问,这将不起作用。它可能已经"解析"了"json-object"而不是字符串。

不需要将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;
        });    
});

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

尝试使用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!');
    }
});  

在某些情况下,服务器可能无法正确返回响应。你有没有试过像这样处理实际的响应代码(例如,如果你的服务器返回200):

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