在过去的几天里,我一直在努力解决这个问题。事实上,由于我对这一切都不熟悉,所以我似乎一直在试图弄清楚一些事情。无论如何,关于我的问题。
我正在尝试在 PHP 中编码一个数组,并使用以下代码使用 JSON 在 JQuery 中检索它:
'core/init.php' 中包含的函数:
function output_errors($errors) {
echo json_encode($errors);
}
登录.php:
<?php
include 'core/init.php';
logged_in_redirect();
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'Please enter a username and password.';
} else if (user_exists($username) === false) {
$errors[] = 'We can\'t find that username. Have you registered?';
} else if (user_active($username) === false) {
$errors[] = 'You haven\'t activated your account.';
} else {
$login = login($username, $password);
if ($login === false) {
$errors[] = 'That username/password combination is incorrect.';
}
else {
//start session
$_SESSION['user_id'] = $login;
//redirect to home.
header('Location: index.php');
exit();
}
}
} else {
header('Location: index.php');
}
include 'includes/overall/header.php';
if (empty($errors) === false) {
?>
<h2>We tried to log you in but...</h2>
<?php
output_errors($errors);
}
include 'includes/overall/footer.php';
?>
查询:
function logErrors(errors) {
alert(errors);
};
$(document).ready(function() {
$.getJSON('login.php', function(errors){
logErrors(errors);
});
});
我在本地工作并且已经让它工作一个测试文件:
测试.php:
<?php
function output_errors($errors) {
echo json_encode($errors);
}
output_errors($errors);
?>
在我的一些研究中,我发现 PHP 的版本可能是一个问题。这似乎不是我的问题,因为我已经让它与另一个文件一起工作。
其他人似乎遇到的另一个常见问题是 $.getJSON 是异步的,并且可能在 php 有机会返回数组之前运行。我不确定我的 JQuery 结构是否正确以避免该问题。
我一直得到的是没有警报,并且错误回显如下:[“我们找不到该用户名。您注册了吗?”]。
如何让我的 JQuery 检索编码数组并触发函数 logErrors?
提前感谢你们可以提供的任何帮助。对不起,如果我发布了太多或不够的代码......新手错误。
更新
以下是 user_exists 和 user_active 函数:
用户存在:
function user_exists($username) {
$username = sanitize($username);
$query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'");
return (mysql_result($query,0) == 1) ? true : false;
}
用户活动:
function user_active($username) {
$username = sanitize($username);
$query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'AND `active` = 1");
return (mysql_result($query,0) == 1) ? true : false;
}
乙