gpt4 book ai didi

javascript - 使用http请求从数据库获取数组

转载 作者:行者123 更新时间:2023-11-28 03:22:20 25 4
gpt4 key购买 nike

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

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

我的代码:

functions.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();

functions.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 响应。

最佳答案

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

TLDR; Javascript 文件中的 this.responseText 包含 php 数组

关于javascript - 使用http请求从数据库获取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59016587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com