【发布时间】:2014-11-12 09:57:02
【问题描述】:
很抱歉,如果这个问题已经被问过,但其他问题的其他答案都没有帮助我解决我的问题。
我正在编写一个用户登录过程,它使用.ajax() 调用我的login.php 文件来登录用户。但是,经过几个小时的调试,我似乎发现问题在于我的ajax 调用中的data: {user: username, pass: password}line 似乎没有将数据发送到login.php 中的$_POST 数组。事实上,它甚至不会在login.php 中回显我的if 声明。我知道这个问题听起来和其他人很相似,但我确实尝试了这个网站上与该主题相关的所有内容,但没有任何运气。
这里是login_form.php。它在底部包含.ajax() 代码:
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
<link rel="stylesheet" type="text/css" href="css/custom-style.css" media="screen">
</head>
<body>
<div id="login_container">
<img src="img/sflogo.gif" alt="Sutton Ferneries" id="sflogo_login">
<p id="add_err">We're sorry, we weren't able to find that username/password.</p>
<input type="text" name="username" id="username" placeholder="Username">
<input type="password" name="password" id="password" placeholder="Password">
<p id="learn_login">Want to know the benefits of having an online account with us? <a href="#">Learn More.</a></p>
<button id="login_btn">Log In</button>
</div>
</body>
<script type="text/javascript">
$(document).ready(function() {
$("#add_err").css('display', 'none', 'important');
$("#login_btn").on("click", function(e) {
e.preventDefault();
var username = $("#username").val();
var password = document.getElementById("password");
password = password.value;
$.ajax({
url: "login.php",
data: { user: username, pass: password },
type: "POST",
dataType: "json",
beforeSend: function() {
$("#add_err").css('display', 'block', 'important');
$("#add_err").html("Loading...");
},
success: function(data) {
document.write(data);
if (data == 'true') {
$("#login_container").html(data);
//closeLightbox();
window.location = "index.php";
} else {
$("#add_err").css('display', 'block', 'important');
$("#add_err").html("Wrong username or password.");
}
}
});
});
});
</script>
</html>
这里是login.php:
<?php
header("Content-Type: application/json, true");
if (!isset($_POST)) {
echo 'Post is null';
} else {
echo 'Everything seems to be okay.';
}
$username = $_POST['user'];
$password = $_POST['pass'];
?>
【问题讨论】:
-
dataType: "json",- 您期望/尝试发送json类型和数据,但从服务器回显文本/html。请尝试类似echo json_encode('Post is null'); -
我也只是试了一下,没有运气。它不会向
success:调用发送任何数据。
标签: php jquery arrays ajax post