【发布时间】:2015-05-07 08:47:19
【问题描述】:
我将从 mySQL 表读取的简单关联数组回显到我的 jquery b.m.o json_encode($array) 方法。但是,我的 .ajax 调用在 jquery 中失败了,这似乎是由于该对象不是有效的 json 对象。我在 chrome 中进行了一些调试,并在网络选项卡下验证了响应预览-确实看起来是完美的 json 格式:
{"用户名":"DehanL","UserPassword":"admin","UserEmail":"dehan@rocketmail.com"}
这是我的 php:
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbName ="dbPodiumPro";
$inUsername = $_POST["name"];
$inPassword = $_POST["password"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Use the dbPodiumPro
mysqli_select_db($conn,"dbPodiumPro");
$sql = "SELECT * FROM users WHERE UserName='$inUsername' AND UserPassword ='$inPassword' ";
$result = mysqli_query($conn,$sql);
// Fetch one row
$row=mysqli_fetch_assoc($result);
//Check to see if the username and password combo exists
if(!empty($row['UserName']) AND !empty($row['UserPassword']))
{
//$_SESSION['UserName'] = $row['UserPassword'];
//echo $_SESSION;
echo json_encode($row);
}
else { echo "Be gone imposter!"; }
$conn->close();
?>
</body>
</html>
然后是jquery:
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: 'php/loginrequest.php', // the url where we want to POST
data: formData, // our data object
dataType: 'json' // what type of data do we expect back from the server
})
// using the done promise callback
.done(function (data) {
console.log("ajax done callback");
})
.fail(function (data) {
console.log(data, "ajax failed callback");
var IS_JSON = true;
try {
var json = $.parseJSON(data);
} catch (err) {
IS_JSON = false;
}
console.log(IS_JSON);
});
【问题讨论】:
-
你在服务器上使用
Content-Type: application/json了吗?否则,即使文本格式正确,客户端也可能认为它不是有效的 JSON -
危险:你很容易受到SQL injection attacks的影响,你需要defend你自己。
-
危险:“根本没有散列”是an unsuitable hashing algorithm;您需要take better care 的用户密码。
-
您的代码可以注入 SQL,但这与您的问题无关。请注意,您可能会使用
' OR 1 OR ''='或类似密码登录。还要对密码使用散列! -
您是否将密码编码为 md5 如果是,请检查此stackoverflow.com/a/30097151/2536812
标签: javascript php jquery json