JSON如果值未定义,则执行某些操作

时间:2011-08-15 18:16:55

标签: php jquery json

对于愿意帮助初学者的人来说,这是一个简单的要点。使用JQuery表单和验证插件提交带有PHP的表单,并在满足某些条件时创建MySQL记录。我将响应作为JSON返回,如果服务器端验证显示OK,我希望表单为slideUp,或者在包含表单的div之前添加错误消息,如果有错误则保留表单。我已经获得了有效的JSON响应,使用以下方式回显:

<?php

$errors = array();
$reqs = array('userName', 'Pwd', 'firstName', 'lastName', 'email', 'cellPhone', 'homePhone', 'role');
foreach($reqs as $req) {
    if((!isset($_POST[$req])) || (empty($_POST[$req]))) {
            $newerr = array('response' => "The field " . $req . " is required.");
            array_merge(array($errors), array($newerr));
            echo json_encode($newerr);
    }
}

if(is_null($errors)) {
    $auser = new User();
    $hshd = sha1($_POST['Pwd']);
    $auser->userName = $_POST['userName'];
    $auser->hshdPwd = $hshd;
    $auser->firstName = $_POST['firstName'];
    $auser->lastName = $_POST['lastName'];
    $auser->email = $_POST['email'];
    $auser->cellPhone = $_POST['cellPhone'];
    $auser->homePhone = $_POST['homePhone'];
    if(!is_null($_POST['school'])) {
    $auser->school = $_POST['school'];
    } else {
        $auser->school = "0";   
    }
    $auser->prelim_role = $_POST['role'];
    $auser->approved = $_POST['approved'];
    if($auser->create()) {
        $abc = array('response'=>"Request successfully submitted. Your account must be configured before you can access the user panel. Please watch for an email confirming your registration and configuration.");
    } else { 
        $abc = array('response'=>"An unknown error occurred. Please send an email to info@aSite.com describing the error event.");
    }
    echo json_encode($abc);
}

?>

JS的相关部分:

submitHandler: function(form) {

$("#frmPrntRgstr").ajaxSubmit({
                                                        dataType: 'json',
                                                        success:    processJson,
                                                        })
                            }
});
function processJson(data) { 
        $("#frmPrntRgstr").slideUp("normal", function() {
            $("#frmPrntRgstrRspns").append(data.response).slideDown("normal");
        })
        }
});

但是使用此设置,错误和成功消息都在JSON对象中具有'response'的键。无论是否有错误,表格都会向上滑动。我正在考虑类似于PHP中if(array_key_exists)的东西。所以if(array_key_exists('errors', $response))然后只是前置,但if(array_key_exists('success', $response))追加并向上滑动。仅限于JSON。

修改

这似乎现在正在起作用。感谢Marc B和公民康纳。如果这种结构存在明显的问题或限制,请告诉我。

<?php  header("Content-type: application/json"); ?>

<?php

$errors = array();

$reqs = array('userName', 'Pwd', 'firstName', 'lastName', 'email', 'cellPhone', 'homePhone', 'role');
foreach($reqs as $req) {
    if((!isset($_POST[$req])) || (empty($_POST[$req]))) {
            $newerr = array("error" => "The field " . $req . " is required.");
            $errors[] = $newerr;
    }
}

if(!empty($errors)) {
echo json_encode($errors, JSON_FORCE_OBJECT);
} else {
    $auser = new User();
    $hshd = sha1($_POST['Pwd']);
    $auser->userName = $_POST['userName'];
    $auser->hshdPwd = $hshd;
    $auser->firstName = $_POST['firstName'];
    $auser->lastName = $_POST['lastName'];
    $auser->email = $_POST['email'];
    $auser->cellPhone = $_POST['cellPhone'];
    $auser->homePhone = $_POST['homePhone'];
    if(!is_null($_POST['school'])) {
    $auser->school = $_POST['school'];
    } else {
        $auser->school = "0";   
    }
    $auser->prelim_role = $_POST['role'];
    $auser->approved = $_POST['approved'];
    if($auser->create()) {
        $success = array('response'=>"Request successfully submitted. Your account must be configured before you can access the user panel. Please watch for an email confirming your registration and configuration.");
        echo json_encode($success);
    } else { 
        $failure = array('error'=>"An unknown error occurred. Please send an email to info@aSite.com describing the error event.");
        echo json_encode($failure);
    }

}

?>

使用JS回调:

function processJson(data) {
    if(data.response) {
        $("#frmPrntRgstr").slideUp("normal", function() {
            $("#frmPrntRgstrRspns").append(data.response).slideDown("normal");
        })
    } else {
        $("#frmPrntRgstr").prepend(data[0].error);
    }
}
});

2 个答案:

答案 0 :(得分:0)

如果您期待JSON,则应使用$.getJSON

function processJson(data) { 
    if(!data.response.errors){
        $("#frmPrntRgstr").slideUp("normal", function() {
          $("#frmPrntRgstrRspns").append(data.response).slideDown("normal");
        })
    }
});

答案 1 :(得分:0)

您可以使用以下内容:

(typeof data.response == "undefined")

如果您希望发现错误,请使用:

    ("#frmPrntRgstr").ajaxSubmit({
                                                        dataType: 'json',
                                                        success:    processJson,
                                                        error: catchError
                                                        })
                            }
})

function catchError(jqXHR, textStatus, errorThrown){
}
function processJson(data) { 
        $("#frmPrntRgstr").slideUp("normal", function() {
            $("#frmPrntRgstrRspns").append(data.response).slideDown("normal");
        })
        }
});