gpt4 book ai didi

javascript - 从表行到详细信息的 AJAX 请求

转载 作者:行者123 更新时间:2023-11-29 12:22:48 25 4
gpt4 key购买 nike

这是我第一次来这里,所以如果我不太能适应你们所有人,我很抱歉。

在学习 AJAX 的过程中,所以我是全新的,但需要为我们的员工网站完成一个页面。

<小时/>

我有一个页面(php),它通过所有患者的 mysql 查询构建一个列表。我对此完全没有问题。然而,我被困在这部分。

当用户单击特定行(又名患者姓名)时,我希望它在右侧的 mysql 数据库中提取与其关联的患者的详细信息,这样页面就不必刷新他们不会被定向到任何其他页面。

我见过这样的例子,当涉及到客户时,比如你点击名字,右边就会出现一个包含电子邮件、电话等的 div。

有人有什么好的起点吗?我已尽我所能进行搜索,但我开始认为在搜索答案时我没有使用正确的语言。

提前谢谢...马特

最佳答案

使用 jQuery。首先,您需要在您的服务器上创建一个 Web 服务。 Web 服务将接受一个 POST 参数,该参数可以是患者姓名或患者 ID。根据此 ID/名称,您将查询 MySQL 数据库,获取所有详细信息并以 json 形式返回。

在前端,您可以使用 jQuery.post()。您将需要传递适当的 URL 和数据。作为返回,您将获得 JSON 数据。在 jQuery.post/$.post 的成功回调方法中,您可以在右侧创建一个 div 并显示这些数据。

如果要返回json格式的数据,也可以直接使用$.postJSON()

请确保在您的 PHP Web 服务中设置适当的 header 。这两个可能是最重要的

Content-Type: application/json // if you are gonna return the data in JSON format
Access-Control-Allow-Origin: * // to let the browser pass the data to the DOM model. This is to allow CORS (Cross Origin Resouce Sharing)

示例:

示例.php

<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
if (isset($_POST['patientID'])) {

$patientID = $_POST['patientID'];
$data = array();

// Enter the appropriate details below
$mysqli = new mysqli("host", "username", "password", "db_name");

/* check connection */
if ($mysqli->connect_errno > 0) {
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}

$statement = $mysqli->prepare("SELECT * FROM `patients` WHERE `patientID` = ? LIMIT 1");
$statement->bind_param('i', $patientID);
$statement->execute();

// You need to write a variable for each field that you are fetching from the select statement in the correct order
// For eg., if your select statement was like this:
// SELECT name, COUNT(*) as count, id, email FROM patients
// Your bind_result would look like this:
// $statement->bind_result($name, $count, $id, $email);
// PS: The variable name doesn't have to be the same as the column name
$statement->bind_result($id, $name, $email, $phone);
while ($statement->fetch()) {
$data["id"] = $id;
$data["name"] = $name;
$data["email"] = $email;
$data["phone"] = $phone;
}
$statement->free_result();

echo json_encode($data);
}

示例.html

<a href="" id="123" onclick="return getPatientData(this);">Patient #123</a>

示例.js

function getPatientData(element) {
var patientID = $(element).attr("id");
$.post("example.php", {"patientID": patientID}, function (data) {
// display the data in appropriate div
}, 'json');
return false;
}

关于javascript - 从表行到详细信息的 AJAX 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28778753/

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