使用数据属性并将其用于XMLHTTP请求



我有一个名为";数据id";并且其值为"0";1〃;。1是我数据库中一辆车的id号。

<div class="row">
<button type="button" class="btn" data-id="1">View Car Details</button>
</div>

当它被点击时,我想把这个id传递给我的JavaScript,在那里它将使用XMLHttpRequest把这个id发送给我的PhP。这是我为JavaScript 所做的

<script>
const buttons = document.querySelectorAll("[data-id]");
buttons.forEach(button => {
button.addEventListener("click", (loadCarDetails));
});
document.getElementById('car-details').addEventListener('click', loadCarDetails);
function loadCarDetails() {
let xhr = new XMLHttpRequest();

xhr.open('GET', 'getCarDetails.php', true);
xhr.onload = function () {
if (this.status == 200) {
let carDetails = JSON.parse(this.responseText);
console.log(cars);

//document.getElementById('users').innerHTML = output;
}
}
xhr.send();
}
</script>

我需要以某种方式获取id并将其传递给getCarDetails.php,它将使用jSON返回汽车的详细信息。我需要使用id在getCarDetails.php中执行查询。这是我的PHP。

$connection = new mysqli("sever", "username", "password", "database");
$car_id = $_POST['car_id];
if ($connection->connect_error){
exit("Error connecting to the database");
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection->set_charset("utf8mb4");

$car_id = $connection->escape_string($_POST['car_id']);

$stmt = $connection->prepare("SELECT car_drivetrain_lookup.drivetrain_type, car_suitability_lookup.car_suitability_type
FROM cars
INNER JOIN car_suitability_lookup ON car_suitability_lookup.lookup_id = cars.car_suitability_id
INNER JOIN car_drivetrain_lookup ON car_drivetrain_lookup.lookup_id = cars.car_drivetrain_id
WHERE cars.car_id = ?");
$stmt->bind_param("i", $car_id);
$stmt->execute();
$result = $stmt->get_result();
echo json_encode($result->fetch_all());

有人能帮我做到这一点吗?我真的是JavaScript的新手,我希望能被引导到正确的方向。

这有两个方面:

  1. 从单击的元素中获取id,以及
  2. 向服务器发送正确类型的请求

第一部分很简单。您的loadCarDetails函数是以事件对象作为第一个参数调用的,它有一个currentTarget属性,引用了您将函数挂接到的元素,因此我们可以从中获得data-*属性:

function loadCarDetails(event) {
const id = event.currentTarget.getAttribute("data-id");
// ...
}

然后,我们需要用id作为car_id来执行POST(您当前的代码执行GET(。我不会在新代码中使用XMLHttpRequest,它已经过时了;我会使用fetch:

function loadCarDetails(event) {
const id = event.currentTarget.getAttribute("data-id");
const body = new FormData();
body.append("car_id", id);
fetch("getCarDetails.php", {
method: "POST",
body
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
return response.json();
})
.then(carDetails => {
// ...use the car details here...
})
.catch(error => {
// ...handle/reject error here...
});
}

最新更新