javascript - 从 XMLHttpRequest 返回多个数据/响应文本
问题描述
我有一个 js 函数,它调用 xml 请求以从单独的 php 文件中获取数据。我可以通过echoing
它从单独的 php 文件中获取返回的数据。
这是我当前的代码:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if(this.readyState == 4 && this.status == 200)
{
//On Data Receive
countryHeader.innerHTML = this.responseText;
}
};
xhttp.open("GET", "country.php?c=" + countryName, true);
xhttp.send();
在我的 php 上:
include("conn.php");
$c = htmlentities($_GET["c"]);
$sec_country = mysqli_real_escape_string($con, $c);
//Searches the db
$sql = "SELECT * FROM countries WHERE country_code = '$sec_country' LIMIT 1";
$result = mysqli_query($con, $sql);
$count = mysqli_num_rows($result);
if($count == 1)
{
//Get Data
$row = mysqli_fetch_assoc($result);
$countryName = $row['country_name'];
$countryPrice = $row['country_price'];
echo $countryName." is worth $".$countryPrice;
}
else
{
//Invalid Code/No Data
echo "No Country Found";
}
如果我发送一个国家代码,例如rus
,它将Russia is worth $1B
主要从 返回echo $countryName." is worth $".$countryPrice;
但是如果我想单独发送$countryName
和$countryPrice
?
例如responseText.a
和responseText.b
解决方案
您可以从 PHP 发送 JSON 响应。这是一个参考-> https://www.w3schools.com/js/js_json_php.asp
推荐阅读
- jquery - 如何在间隔和动画中提高每次点击 div 的速度?
- delphi - 无法调用 MessageDlg
- node.js - 从 Visual Studio 将节点应用程序部署到谷歌云
- amazon-web-services - AWS ALB DNS 的安全性
- javascript - 使用 Kotlin 和 External 创建 React 应用程序
- numpy - 如何将 numpy 数组邻接列表转换为 numpy 数组邻接矩阵?
- javascript - Gatsby 静态/动态混合组件
- javascript - Html 不显示 Typescript 的结果
- python - SQLAlchemy:如何引用过滤字段
- swift - Swift 中的类型 '()' 指的是什么