【问题标题】:How do I retrieve data from an xhr request?如何从 xhr 请求中检索数据?
【发布时间】:2019-11-26 15:24:41
【问题描述】:

这是我的情况:

我有一个创建 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.ini 中返回 $result 变量中的数据。有没有办法做到这一点?

【问题讨论】:

  • 您的意思是从您的fillTestsTable javascript 函数返回数据吗?
  • @RamRaider 不,我的意思是从 ./db-queries/get-tests.php 文件中执行的代码中返回数据。
  • Quentin 建议使用 echoprint - 您也可以在 PHP 代码中使用 exit()die()echoed 的格式取决于您想用它做什么 - 它可以是纯文本、html、xml、json 或其他...使用循环遍历记录集并回显/打印数据
  • @RamRaider 好的。后续问题:是否有一个 xhr 字段或方法可以存储这些数据?例如,是否有 xhr.response 或 xhr.getResponse() 可以将我正在回显的数据返回给我?我查看了 mozilla api,但找不到完全合适的。
  • 我的目标是在 php 中获取 $result 变量的内容,以便我可以在 javascript 中使用。有没有更好的方法来解决这个问题?

标签: javascript php xmlhttprequest


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    <?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>
    

    【讨论】:

      猜你喜欢
      • 2011-12-22
      • 1970-01-01
      • 1970-01-01
      • 2019-10-28
      • 2020-05-17
      • 2017-03-09
      • 2017-06-16
      • 1970-01-01
      相关资源
      最近更新 更多