[英]AJAX status 200 fires error on PHP echo of json_encode
Everything works fine with following program, except AJAX error fires: 使用以下程序,一切正常,但会引发AJAX错误:
javascript: javascript:
var data = {
email: 'me@gmail.com',
password: 'secretword'
};
$.ajax({
type: "POST",
dataType: "application/json",
url: "http://localhost/CFBserver/validateUser.php",
data: data,
success: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
} }
php: 的PHP:
<?php
$conn = mysqli_connect('localhost', 'root', '', 'cfbdata');
if (mysqli_connect_errno($conn)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$sql = "SELECT * FROM users WHERE email = '$email' AND password = '$password'";
if (!mysqli_query($conn, $sql)) {
die('Error: ' . mysqli_error($conn));
}
$result = mysqli_query($conn, $sql);
$numrows = mysqli_num_rows($result);
if ($numrows > 0) {
$message = array('result' => 'found',
'email' => $email,
'password' => $password,
);
} else {
$message = array('result' => 'Not found',
'email' => $email,
'password' => $password,
);
}
header('Content-type: application/json');
echo json_encode($message);
mysqli_close($conn);
?>
This is what console displays: 这是控制台显示的内容:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
{"result":"found","email":"me@gmail.com","password":"secretword"}
</body>
</html>
So php finds the record in the mysql database but on return to AJAX, error fires. 因此,php在mysql数据库中找到记录,但返回AJAX时,会引发错误。 Why is this?
为什么是这样?
Your AJAX is expecting a JSON response, but is getting HTML. 您的AJAX期待JSON响应,但获取HTML。 That's why the request returns status code 200 (= OK), but your JS won't work.
这就是为什么请求返回状态代码200(= OK),但是您的JS无法使用的原因。
PHP's json_encode
doesn't add HTML by itself, so you're probably outputting to a template (or you've wrapped your PHP in HTML). PHP的
json_encode
本身不会添加HTML,因此您可能正在输出到模板(或者您已将PHP封装为HTML)。
As others have also mentioned, you're open to SQL injection . 正如其他人也提到的那样,您可以进行SQL注入 。 There is also no way to be sure your error method is firing, since both your AJAX'
error
and success
do the same thing. 也没有办法确保您的错误方法正在触发,因为您的AJAX
error
和success
都做同样的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.