php - ajax 从 php 页面和 mysqli 加载数据
问题描述
我有一个包含x
变量信息的数据库。我想要一个 php 页面,它使用 ajax 和我的 phpapi 页面从 mysqli 加载数据。所以我创建了我的数据库,它每 1 分钟填满一次。我创建了一个 php 页面,它从 mysqli 加载数据并输出这是我的 php 页面,它从我的 mysqli 加载数据并且它工作正常
这是myphpapi.php
页面
<?php
$con = mysqli_connect("x.x.x.x","boob","booob");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
mysqli_select_db($con,"sss");
$sql = "SELECT `x` FROM ddd order by id desc limit 1";
$result = mysqli_query($con,$sql);
$result = mysqli_fetch_assoc($result);
$output = json_encode($result);
echo $output;
mysqli_close($con);
?>
这部分运行良好,但我有另一个包含 ajax 的 php 页面。当我按下按钮时,什么也没发生
请帮忙
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax test</title>
</head>
<body>
<h1>
this is ajax test
</h1>
<div id="main">
</div>
<button type="button" id="ajax_button">click me</button>
<script>
replaceText();
function replaceText() {
var target = document.getElementById("main");
var xhr = new XMLHttpRequest();
xhr.open('GET', 'myphpapi.php', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 2) {
target.innerHTML = 'loading . . . .';
}
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
var json = JSON.parse(xhr.responseText);
target.innerHTML = json;
}
xhr.send();
}
}
var button = document.getElementById("ajax_button");
button.addEventListener("click",replaceText);
</script>
</body>
</html>
解决方案
如果您在 ajax 函数中稍微更改顺序并将该send
方法移到onreadystatechange
事件处理程序之外,它应该可以工作〜尽管@Barmar 指出 utJSON.parse
将返回一个对象。
function replaceText() {
var target = document.getElementById("main");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 2) {
target.innerHTML = 'loading . . . .';
}
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
var json = JSON.parse(xhr.responseText);
target.innerHTML = json;
}
}
xhr.open('GET', 'myphpapi.php', true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send();
}
推荐阅读
- swift - 在 Swift 中简化 If-Else If-Then 语句
- c++ - C++11 复杂
* 到 C 浮点复数 * - java - JSF PrimeFaces 在服务器端对 DataTable 进行分页
- regex - vee 验证正则表达式不起作用
- python - pyldap 和 microsoft ldap 的问题
- javascript - 为现有 JavaScript 进行 TypeScript 声明
- batch-file - 如何使用命令提示符秘密启动网站
- angular - 量角器:突然出现错误元素不可见
- angular - 如何将角度文件放入快递服务器?
- angularjs - 在打印窗口中隐藏浮动面板