簡體   English   中英

ajax從php頁面和mysqli加載數據

[英]ajax load data from php page and mysqli

我有一個數據庫,其中包含有關x變量的信息。 我想擁有一個從ajax和phpapi頁面從mysqli加載數據的php頁面。 因此我創建了數據庫,數據庫每1分鍾填滿一次。 我創建了一個從mysqli加載數據並輸出的php頁面,這是我的從mysqli加載數據的php頁面,它正常工作

這是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 JSON.parse指出ut將返回一個對象。

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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM