【发布时间】:2012-03-01 09:23:37
【问题描述】:
长期阅读,第一次海报。我对 jQuery 和 JSON 的世界非常陌生,并且发现我正在运行的登录脚本存在问题。
最终目标是从表单中捕获数据,将该数据传递到 PHP 文件以通过 jQuery.ajax() post 进行处理,将数据与 MySQL 数据库进行比较以进行身份验证,并返回成功或失败的数据.
我的问题是我无法将 JSON 格式的数据从 PHP 脚本传递回 jQuery。使用 Chrome 的开发人员工具查看处理时,我看到“登录失败”。我已经通过将数组 $rows 扔到我的 error_log 文件中仔细检查了它,它返回了格式正确的 JSON,但我一辈子都无法让它返回到 jQuery 文件。任何帮助表示赞赏。
我的表单输入:
<!-- BEGIN: Login Page -->
<section data-role="page" id="login">
<header data-role="header" data-theme="b">
<a href="#landing" class="ui-btn-left">Back</a>
<h1>Please Log In</h1>
</header>
<div data-role="content" class="content" data-theme="b">
<form id="loginForm" action="services.php" method="post">
<div data-role="fieldcontain">
<label for="schoolID">School ID</label>
<input type="text" name="schoolID" id="schoolID" value="" />
<label for="userName">Username</label>
<input type="text" name="userName" id="userName" value="" />
<label for="password">Password</label>
<input type="password" name="password" id="password" value="" />
<h3 id="notification"></h3>
<button data-theme="b" id="submit" type="submit">Submit</button>
<input type="hidden" name="action" value="loginForm" id="action">
</div>
</form>
</div>
<footer data-role="footer" data-position="fixed" data-theme="b">
<h1>Footer</h1>
</div>
</section>
<!-- END: Login Page -->
我的 jQuery 处理程序:
// Listen for the the submit button is clicked, serialize the data and send it off
$('#submit').click(function(){
var data = $("#loginForm :input").serializeArray();
var url = $("#loginForm").attr('action');
$.ajax({
type: 'POST',
url: url,
cache: false,
data: data,
dataType: 'json',
success: function(data){
$.ajax({
type: 'GET',
url: "services.php",
success: function(json){
alert(json);
$('#notification').append(json);
}
});
}
});
});
这是我的 PHP 处理:
if (isset($_POST['action'])) {
$schoolID = $_POST['schoolID'];
$userName = $_POST['userName'];
$password = $_POST['password'];
$sql = "SELECT FirstName, LastName, FamilyID, StudentID, UserID ";
$sql .= "FROM Users ";
$sql .= "WHERE SchoolID = '$schoolID' ";
$sql .= "AND Username = '$userName' ";
$sql .= "AND Password = '$password'";
$rs = mysql_query($sql);
$rows = array();
while($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
$row_array['firstName'] = $row['FirstName'];
$row_array['lastName'] = $row['LastName'];
$row_array['familyID'] = $row['FamilyID'];
$row_array['studentID'] = $row['StudentID'];
$row_array['userID'] = $row['UserID'];
array_push($rows, $row_array);
}
header("Content-type: application/json", true);
echo json_encode(array('rows'=>$rows));
exit;
}else{
echo "Login Failure";
}
【问题讨论】:
-
"将该数据传递给 PHP 文件以通过 jQuery 进行处理" jQuery 在客户端上运行。 PHP 在服务器上运行。他们从不见面。
-
我在 jQuery 中使用 $.ajax() 函数将 JSON 数据传递给 PHP。对不起,我没有很好地解释它。
-
为什么需要进行 2 次 ajax 调用?在这种情况下,为什么只显示 1 个 php 脚本,而不是 2 个?
-
我不确定它是否正确,但从我收集的内容来看,我必须使用 $.ajax() 来发布序列化数据,然后在成功函数中使用 $.ajax () 来获取 JSON 数据。我有一个偷偷摸摸的怀疑,我在这个假设中是非常错误的。