【发布时间】:2020-04-18 07:49:51
【问题描述】:
我正在使用 PHP-MYSQL 学习 AJAX。
我有三个文件 index.php、process.php 和 database.php...
Javascript 包含在 index.php 中。
index.php
<main>
<header>
Displaying MYSQL errors
</header>
<!-- Display error -->
<section id="error"></section>
<div id="submit_div">
<button id="submit" name="submit_btn">Submit</button>
</div>
</main>
Javascript
<script>
let submit_btn = document.getElementById('submit');
let error = document.getElementById('error');
function showHint() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "process.php", true);
xhr.setRequestHeader('X-Requested-with', 'XMLHttpRequest');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var simple_text = xhr.responseText;
error.innerText = simple_text; //print the error.
} // if
} // onreadystatechange()
// Sending the request
xhr.send();
} //showHint()
submit_btn.addEventListener('click', function() {
showHint();
}, false);
</script>
process.php
<?php
require_once('database.php');
$db = db_connect();
?>
database.php
<?php
define("DB_SERVER", "localhost");
define("DB_USER", "abhishek");
define("DB_PASS", "wrongpassword"); // I set the wrong password to print the error.
define("DB_NAME", "ajax");
function db_connect(){
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
confrim_db_connect();
return $connection;
}
function confrim_db_connect(){
if(mysqli_connect_errno()){
$msg = "Database connection failed: ";
$msg .= mysqli_connect_error();
$msg .= " (" . mysqli_connect_errno() . ")";
exit($msg);
}
}
?>
所以现在点击按钮,ajax 请求启动并将请求发送到 process.php 页面,该页面在xhr.responseText 中返回响应。
请注意,在database.php 中,我输入了错误的数据库密码以得到错误响应。
所以当我按下按钮获取 xhr.responseText 的内容时。
它给出了xhr.responseText 的内容(这就是我想要的)-
警告:mysqli_connect(): (HY000/1045): /var/www/html/ 中的用户 'abhishek'@'localhost' 的访问被拒绝(使用密码:YES) AJAX/sql_ajax/database.php 上线 5
数据库连接失败:用户 'abhishek'@'localhost' 的访问被拒绝(使用密码:YES)(1045)
我还没有问题。
但是如果我使用 JSON 解析结果
var in_json = JSON.parse(xhr.responseText);
然后它给了我错误 -
VM949:1 Uncaught SyntaxError: Unexpected token
所以问题是json无法解析结果。
所以现在我的问题是 -
如何在 json 中解析上述结果?
我已经知道如何在 jquery 中打印错误。
在这里使用 javascript 帮助...
请再次阅读我的问题,我添加了更多信息...
【问题讨论】:
-
xhr.readyState == 4 && xhr.status == 200这意味着“如果 HTTP 响应代码是 200”(所以一切都很好),在你必须写else if(xhr.status == 500) do somethig...并做某事之后执行该块内的操作是您将用来显示错误的代码,因为如果 PHP 脚本中有错误,将返回 500 HTTP 响应 -
@AlbertoSinigaglia 谢谢,我认为您已经接近我的答案,但请再次阅读我的问题,因为我在其中添加了更多信息。
-
为什么要用json解析错误?它只是纯文本,因此您只需将 simple_text 分配给 error.innerHTML (如果请求状态为 500 )
-
@AlbertoSinigaglia 根据您的回答,PHP 脚本没有错误,我只是输入了错误的密码来连接数据库并通过 AJAX 打印该错误。
-
那么你只需要在解析
try { let json = JSON.parse(response); } catch(e) { alert(e); // error in the above string (in this case, yes)! }时尝试并捕捉任何错误@