Ajax发布到php>使用xmlhttprequest获取php变量

Ajax post to php > get php variable with xmlhttprequest

本文关键字:php 使用 xmlhttprequest 获取 变量 Ajax gt      更新时间:2023-09-26

我想每隔几秒钟用javascript更新一次我的表。

到目前为止,我向update.php发出了ajax post请求,并设置了触发器if。然后执行mysql查询,并将结果集放入json变量中。

之后,我通过XMLHttpRequest获得它。

问题是每个XMLHttpRequest示例都使用echo-json。但是当我把echo-json放在isset后检查中时,它不会返回任何内容不再

我认为问题是它不能回声

这是我的代码:

PHP

if (isset($_POST["updateTable"])) {
        $result = mysqli_query($con,"SELECT * FROM users");
        $row = mysqli_fetch_row($result);
        $rsArray[] = array();
        while ($row) {
            $rsArray[] = $row;
            $row = mysqli_fetch_row($result);
        }
        echo json_encode($rsArray);
    }

AJAX

var updateTable = "true";
    setTimeout(function(){ 
        $.ajax({
            type: 'POST',
            url: '../EXT_PHP/update.php', 
            data: { updateTable: updateTable }
        });
        console.log(updateTable);
    }, 3000);

xmlhttpRequest

setTimeout(function(){ 
    var oReq = new XMLHttpRequest(); 
    oReq.onload = function() {
        alert(this.responseText);
    };
    oReq.open("get", "../EXT_PHP/update.php", true);
    oReq.send();
}, 3000);

您是否尝试过将PHP脚本的头设置为JSON?

header('Content-Type:application/json'(;

请注意,必须在Programm(即第一个回波(的第一次输出之前设置标题

<?php
header('Content-Type: application/json');
if (isset($_POST["updateTable"])) {
        $result = mysqli_query($con,"SELECT * FROM users");
        $row = mysqli_fetch_row($result);
        $rsArray[] = array();
        while ($row) {
            $rsArray[] = $row;
            $row = mysqli_fetch_row($result);
        }
        echo json_encode($rsArray);
    }

如果doenst仍然有效,那么您应该检查jsonencode函数中是否存在任何错误,即按时间编码存在一些问题。使用

echo json_last_error_msg();

为此。