简体   繁体   English

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

[英]Ajax post to php > get php variable with xmlhttprequest

I want to update my table with javascript every couple seconds. 我想每隔几秒钟用javascript更新我的表格。

So far I made an ajax post request to my update.php and trigger if is set. 到目前为止,我向我的update.php发出了ajax发布请求,并触发了if设置。 Then do a mysql query and put the resultset in a json variable . 然后执行mysql查询 ,并将结果集放入json变量中

After this i get it with a XMLHttpRequest . 之后,我用XMLHttpRequest得到它。

The problem is that every XMLHttpRequest example uses echo json. 问题是每个XMLHttpRequest示例都使用echo json。 But when I put my echo json in my isset post check it wont return anything anymore. 但是,当我将我的echo json放在isset post中时,它将不再返回任何内容。

I think the problem is that it can't echo ? 我认为问题在于它无法回响吗?

This is my code: 这是我的代码:

PHP : 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 : AJAX

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

xmlhttpRequest : xmlhttpRequest

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

Have you Tried to set the header of you PHP Script to JSON? 您是否尝试过将PHP脚本的标头设置为JSON?

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

Note that the header must be set before the first output of your Programm (iE the first echo) 请注意,标头必须设置在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);
    }

if that doenst work still you should check if there has been any errors within the json_encode function, there are some problems with encoding by time. 如果该操作仍然有效,则应检查json_encode函数内是否存在任何错误,按时间编码存在一些问题。 Use 采用

echo json_last_error_msg();

for this. 为了这。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM