javascript - 使用 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 响应。
解决方案
基本上,您从您的 js 脚本请求您的 PHP 脚本,并期望来自 PHP 文件的响应,这是您想要的数组,可以在您的 Javascript 中访问this.responseText
。
TLDR;this.responseText
在你的 Javascript 文件中有 php 数组
推荐阅读
- jmeter - 将 java 代码转换为 beanshell 采样器 (JMETER)
- r - 通过 NoData 拆分数值向量
- amazon-web-services - AWS 转录 | 无法通过 SDK 使用表格创建自定义词汇表
- hazelcast - 如果为区域配置了 MapLoader 的后写队列,它们是否会持久保存到 Hazelcast 热重启存储
- android - 在 Android ARCore 中检测二维码
- javascript - 移动设备上的 onClick 事件后功能没有反应
- javascript - 在节点 js 中使用 java 脚本函数
- ios - 从 UIWebview 迁移到 WKWebview
- angularjs - 我可以将 ng-switch 与 ng-repeat 一起使用吗?
- java - 在 JFreechart 中将 unix 时间转换为日期?