ajax从php页面和mysqli加载数据

问题描述 投票:0回答:1

我有一个包含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>
php ajax mysqli load
1个回答
0
投票

如果你在ajax函数中稍微改变一下顺序并将send方法移到onreadystatechange事件处理程序之外它应该工作〜虽然如@Barmar指出的那样JSON.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();
}
© www.soinside.com 2019 - 2024. All rights reserved.