通过Ajax访问PHP值

时间:2018-08-21 11:26:35

标签: javascript php

好吧,所以我基本上想做的就是通过AJAX发送包含密码(预定义,没有DB)的表单。在我的php文件中,我检查了输入,并尝试向JS返回true或false,但这部分失败,因为我无法设法访问该值。这是我的代码:

ajaxRequest.js

// Variable to hold request
var request;

// Bind to the submit event of our form
$(".lockForm").submit(function(event){

// Prevent default posting of form - put here to work in case of errors
event.preventDefault();

// Abort any pending request
if (request) {
    request.abort();
}
// setup some local variables
var $form = $(this);

// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");

// Serialize the data in the form
var serializedData = $form.serialize();

// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);

// Fire off the request to /form.php
request = $.ajax({
    url: "assets/php/lockscreen.php",
    type: "POST",
    data: serializedData,
    dataType: 'text',
    success: function (data) {
        console.log(data.status);
    }
});

// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
    // Log the error to the console
    console.error(
        "The following error occurred: "+
        textStatus, errorThrown
    );
});

// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
    // Reenable the inputs
    $inputs.prop("disabled", false);
});

});

lockscreen.php

<?php


// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$pass = isset($_POST['pass']) ? $_POST['pass'] : null;
$response = false;

function CheckInput($pass){

if($pass == "SPV" || $pass == "TEACHERS"){
    $response = true;
    $responseLock['status'] = 'true';
    echo json_encode($responseLock);
} else {
    $response = false;
    $responseLock['status'] = 'true';
    echo json_encode($responseLock);
}

}

?>

到目前为止,我尝试将dataType更改为JSON,但随后输入意外结束。如果我将其保留为“文本”,则每当尝试访问该值时,都会得到“未定义”。如果仅显示console.log,而不尝试访问任何值,则会收到成功消息。我也不知道为什么。

1 个答案:

答案 0 :(得分:1)

调用您的 CheckInput 函数:

<?php
$pass     = isset($_POST['pass']) ? $_POST['pass'] : null;
$response = false;

function CheckInput($pass) {
    if($pass == "SPV" || $pass == "TEACHERS"){
        $result = true;
    } else {
        $result = false;
    }

    return array('status' => $result);
}

echo json_encode(CheckInput($pass));
?>