繁体   English   中英

如何从 xhr 请求中检索数据?

[英]How do I retrieve data from an xhr request?

这是我的情况:

我有一个创建 XMLHttpRequest 对象的 JS 函数。 请求被打开,我在指定的 url 上调用“GET”方法。 请求有效,因为它到达 url 目标并执行目标中的代码,但我不确定如何访问目标代码中的变量。

这是我所拥有的:

JS:

function fillTestsTable()
{
    const xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            alert(xhr.responseText);
        }
    }   

    xhr.open("GET", "./db-queries/get-tests.php");
    xhr.send(null);
}

PHP目标文件:

<?php

    $conn = mysqli_connect("localhost:3306"   ,   "exampre2_tplugin"   ,   ",Vyml.F!@(}{"   ,   "exampre2_totaltoefltimeplugin");

    if (!$conn) {
        echo "Error: Unable to connect to MySQL." . PHP_EOL;
        echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
        echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
        exit;
    }

    $sql = "SELECT * FROM TOEFLTESTS";
    $result = mysqli_query($conn, $sql);

    //return $result;
    ?>

我想要做的是返回 php 中 $result 变量中的数据。 有没有办法做到这一点?

在 PHP 中, return用于将值从当前函数返回到调用该函数的位置。

要在 HTTP 响应中输出数据,请使用echoprint

请注意, mysqli_query返回一个 mysqli_result 对象,因此您需要从中提取所需的数据(例如使用fetch_array ),然后将其转换为合适的文本格式(例如使用json_encode )。

例如:如果你想为你的 Ajax 回调函数返回 JSON 格式的数据,你可以这样做:

<?php

    $conn = mysqli_connect("localhost:3306"   ,   "exampre2_tplugin"   ,   ",Vyml.F!@(}{"   ,   "exampre2_totaltoefltimeplugin");

    $data=[];   //store recordset here

    $sql = "SELECT * FROM TOEFLTESTS";
    $result = mysqli_query($conn, $sql);

    if( $result ){ /* iterate through the recordset, add each row to output data */
        while( $rs=$result->fetch_object() ){
            $data[]=$rs;
        }
    }
    /* send data back to the ajax callback function */
    exit( json_encode( $data ) );
?>

有很多方法可以继续执行此操作,但它有助于明确定义目的并确定您的应用程序的工作方式。 然后callback将处理响应数据以向 HTML 表添加新行。 知道回调是做什么通常会(或可能)影响您返回的数据格式 - 在您的情况下,如果它只是 HTML 表中的新行,最好将数据服务器端格式化为 HTML 和发回原始 html 文本。


使用 Ajax 允许您的应用程序请求任何类型的数据而无需重新加载页面(通常是传统的表单提交)

作为在基本 ajax 请求之后填充 HTML 表的基本示例(POST 而不是 GET,但工作原理相同)

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        $dbhost =   'localhost';
        $dbuser =   'root'; 
        $dbpwd  =   'xxx'; 
        $dbname =   'maps';
        $db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

        ob_clean();

        $sql='select `name`,`address`,`lat`,`lng` from `maps` limit 10';
        $res=$db->query( $sql );

        while( $rs=$res->fetch_object() ){
            printf('
                <tr>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                </tr>',
                $rs->name,
                $rs->address,
                $rs->lat,
                $rs->lng
            );
        }
        exit();
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Ajax: fetch data from db - add to table</title>
        <script>
            const ajax=function(url,params,callback){
                let xhr=new XMLHttpRequest();
                xhr.onload=function(){
                    if( this.status==200 && this.readyState==4 )callback.call( this, this.response )
                };
                xhr.open( 'POST', url, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.send( params );
            };
        </script>
    </head>
    <body>
        <input type='button' value='Fetch Data' />
        <table></table>
    </body>
    <script>
        document.querySelector('input[type="button"]').onclick=function(e){
            ajax( location.href, false, function(r){
                this.innerHTML=r
            }.bind( e.target.nextElementSibling ))
        }
    </script>
</html>

暂无
暂无

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

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