ajax从php页面和mysqli加载数据
我有一个包含ajax从php页面和mysqli加载数据,php,ajax,mysqli,load,Php,Ajax,Mysqli,Load,我有一个包含x变量信息的数据库。我希望有一个php页面,通过ajax和我的phpapi页面从mysqli加载数据。所以 我创建了我的数据库,它每1分钟就填满一次。 我创建了一个php页面,该页面从mysqli加载数据并使用 这是我的php页面,它从mysqli加载数据,并且工作正常 这是myphpapi.phppage <?php $con = mysqli_connect("x.x.x.x","boob","booob"); if (!$con) { die('Could no
x
变量信息的数据库。我希望有一个php页面,通过ajax和我的phpapi页面从mysqli加载数据。所以
我创建了我的数据库,它每1分钟就填满一次。
我创建了一个php页面,该页面从mysqli加载数据并使用
这是我的php页面,它从mysqli加载数据,并且工作正常
这是myphpapi.php
page
<?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测试
这是ajax测试
点击我
replaceText();
函数replaceText(){
var target=document.getElementById(“主”);
var xhr=new XMLHttpRequest();
open('GET','myphpapi.php',true);
xhr.onreadystatechange=函数(){
if(xhr.readyState==2){
target.innerHTML='loading….';
}
如果(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_按钮”);
按钮。addEventListener(“单击”,替换文本);
如果在ajax函数中稍微更改顺序,并将send
方法移到onreadystatechange
事件处理程序之外,它应该可以工作~尽管正如@BarmarJSON所指出的那样。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();
}
JavaScript控制台中是否有错误?您是否检查了网络选项卡中的响应以查看JSON是否返回?请注意,即使这样做有效,它也只会在DIV中显示
[Object Object]
。JSON.parse()
返回一个对象,而不是字符串。如果要显示x
的值,它应该是target.innerHTML=json.x
您的ajax代码乱七八糟-在readystatechange
处理程序中有send
方法