【发布时间】:2017-10-31 23:25:48
【问题描述】:
所以我正在编写一个 API,它在前端使用 HTML、JS 和 CSS,在后端使用 PHP,它可以访问我的 SQL 数据库。
我的任务是单击按钮后,创建一个函数,它将以 JSON 编码的信息发送到 .php 文件,我需要将该对象从 JSON 解码为 PHP,然后连接到 SQL 数据库,并将以 JSON 编码的相关信息返回给 HTML 页面,以后的功能将能够更新/删除某些数据。
此 API 使用两个主要页面,即 HTML 和 PHP 文件,以及 SQL 数据库。有人可以告诉我为什么这不起作用以及我该如何解决?为了澄清,我希望能够选择一个单选按钮选项,然后按 app_list_button,这将返回按 app_name 或其评论评级排序的所有应用程序。任何帮助将不胜感激,如果我能够更好地构建任何东西,请告诉我。
index.html
<div id='app_content'>
<label>Refine search by</label>
</br>
<input type="radio" id="name_radio">
<label>Name</label>
</br>
<input type="radio" id="rating_radio">
<label>Rating</label>
</br>
<button id="app_list_button" onclick="load_list_function()">View App List</button>
</br>
<p id='app_list_p'></p>
<input type="submit" name="app_detail_button" value="View App
Details">
</br>
</div>
</div>
</body>
<script>
var app_list_bttn = document.getElementById('app_list_button');
var radio = {};
//List apps
function load_list_function() {
var xhr = new XMLHttpRequest();
//name radio checked
radio.sortByName = document.getElementById('name_radio').checked;
//rating radio checked
radio.sortByRating =
document.getElementById('rating_radio').checked;
document.getElementById('app_list_p').innerHTML = this.responseText;
xhr.open('GET', 'API.php', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(radio));
}
</script>
API.php
<?
$conn = mysqli_connect('localhost', '30319329', 'password', 'Application');
$errors = array();
$json_response = array();
$radio_req = file_get_contents('php://input');
$radio_result = json_decode($radio_req);
//get a list of all apps
//encode into json to send back
if ($radio_result - > sortByName == true) {
//order by name
$results = mysqli_query($conn, "SELECT app_name FROM App");
while ($row = mysqli_fetch_assoc($results)) {
// You can modify the $row here as well, or filter out certain rows
$json_response[] = $row;
}
header("Content-Type: application/json");
echo json_encode($json_response);
} else($radio_result - > sortByRating == true) {
//order by rating
//order by name
$results = mysqli_query($conn, 'SELECT app_name, rating FROM App, App_Review ORDER BY rating ');
while ($row = mysqli_fetch_assoc($results)) {
// You can modify the $row here as well, or filter out certain rows
$json_response[] = $row;
}
header("Content-Type: application/json"); echo json_encode($json_response);
}
$conn - > close();
?>
【问题讨论】:
-
那里发生了很多事情,您需要告诉我们哪段代码不起作用
-
脚本元素,向 php 文件发送请求。我将大部分 php 注释掉,只留下 if 和 else 语句。对不起
-
xhr.open('GET', 'API.php', true)POST吗? -
另外,不推荐使用 PHP 的短开标签。您的环境是否允许
<?而不是<?php? -
是的,应该的,我刚刚改了,还是没有。虽然我都尝试过,但不小心把它留作 GET,而不是 POST。目前我正在使用 标签跟踪我的实验室的结构,所以我真的不知道。我正在使用的编辑器只是 Notepad++,它将是最新版本。