Javascript 通过Ajax访问PHP值
好的,我基本上是想通过AJAX发送一个包含密码(预定义的,没有DB)的表单。在我的php文件中,我检查输入,并尝试将true或false返回给我的JS,但这部分失败,因为我无法访问值。这是我的密码: ajaxRequest.jsJavascript 通过Ajax访问PHP值,javascript,php,Javascript,Php,好的,我基本上是想通过AJAX发送一个包含密码(预定义的,没有DB)的表单。在我的php文件中,我检查输入,并尝试将true或false返回给我的JS,但这部分失败,因为我无法访问值。这是我的密码: ajaxRequest.js // Variable to hold request var request; // Bind to the submit event of our form $(".lockForm").submit(function(event){ // Prevent de
// 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);
}
}
?>
到目前为止,我尝试将数据类型更改为JSON,但随后出现了一个意外的输入结束错误。如果我将其保留为“文本”,每当我尝试访问该值时,就会得到“未定义”。如果我只显示console.log,而不尝试访问任何值,则会收到一条成功消息。我不知道为什么。调用您的
检查输入功能:
<?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));
?>
当您尝试访问什么时,您会在什么地方得到“未定义”?您是否调用过CheckInput
函数?调试并通过日志表单console@fredrik这就是问题所在。谢谢您!