首页 > 解决方案 > 使用 hhtp 请求从数据库中获取数组

问题描述

我的目标是将数据库中的元素添加到下拉菜单中。我在页面加载时调用了一个 javascript 函数,该函数调用 php 文件,将参数 createOptions=true 传递给该 php 文件。然后在 php 文件中检查 createOptions isset 是否成功,然后从数据库中获取我需要的数组。但是我怎样才能将该数组返回到 javascript 文件并填充我的下拉菜单(选择带有选项的标签)?或者我应该从 php 文件中填写菜单?

我正在关注这个简单的教程:https ://www.w3schools.com/xml/xml_http.asp

我的代码:

函数.js 文件:

function showTypes()
{        
    let xmlhttp =  createXMLHttp();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) 
            console.log(this.responseText);
    };
    xmlhttp.open("GET", "../php/functions.php?createOptions=true", true);
    xmlhttp.send();
}

showTypes();

函数.php 文件:

if (isset($_GET['createOptions']))
    addTypesToMenu();

function GetTypesArray()
{
    $db = Connect();
    $Types = array();
    $i = 0;

    $result = mysqli_query($db, "SELECT * FROM works");

    while($row = mysqli_fetch_array($result))
        $Types[$i++] =  $row['work_type'];

    return $Types;
}

function addTypesToMenu()
{
    $Types = GetTypesArray();

    echo $Types;
}

最后一行返回“数组到字符串转换”错误。我想获得可以在 JavaScript 中使用的数组。但除了在 php 文件中回显某些内容外,我不知道任何其他方式来获取 http 响应。

标签: javascriptphpxmlhttprequest

解决方案


基本上,您从您的 js 脚本请求您的 PHP 脚本,并期望来自 PHP 文件的响应,这是您想要的数组,可以在您的 Javascript 中访问this.responseText

TLDR;this.responseText在你的 Javascript 文件中有 php 数组


推荐阅读