我有以下链接;
www.example.com/profile.php?u=aaron
我想使用ajax来获取u=
,以回显在数据库中以名称aaron
保存的详细信息。但是,每当我尝试使用Ajax代码实现这一目标时,最终都会得到空白页。
我的AJAX代码;
$(document).ready(function() {
$.ajax({
type: "GET",
url: "fetch.php",
data: "u=":usr,
success: function(d) {
$("#detail").html(d);
}
});
});
fetch.php;
<?php
// connect to db
include 'db.php';
if (isset($_GET['usr'])) {
$user_query = "SELECT details FROM users_det WHERE name = ?";
if ($stmt = mysqli_prepare($db_var, $user_query)) {
mysqli_stmt_bind_param($stmt, "s", $_GET['usr']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $details);
while (mysqli_stmt_fetch($stmt)) {
// fetch results
}
// close statement
mysqli_stmt_close($stmt);
}
// echo user details
echo $details;
}
?>
我的HTML代码;
<div id="detail"></div>
以及我的HTML代码中的以下PHP代码;
<?php
$user = preg_replace('#[^a-zA-Z0-9_.]#i','',$_GET['u']);
?>
我想知道为什么ajax无法从链接获取名称。
答案 0 :(得分:0)
首先使用 window.location.href 获取完整的URL,实例化一个url对象,然后通过javascript中的 searchParams 获取其参数。
脚本:
var urlString = window.location.href; //www.example.com/profile.php?u=aaron
var url = new URL(urlString);
var usr = url.searchParams.get("u");
$(document).ready(function() {
$.ajax({
type: "GET",
url: "fetch.php",
data: "u="+usr,
success: function(d) {
$("#detail").html(d);
}
});
});
PHP:
<?php
// connect to db
include 'db.php';
if (isset($_GET['u'])) {
$user_query = "SELECT details FROM users_det WHERE name = ?";
if ($stmt = mysqli_prepare($db_var, $user_query)) {
mysqli_stmt_bind_param($stmt, "s", $_GET['u']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $details);
while (mysqli_stmt_fetch($stmt)) {
// fetch results
}
// close statement
mysqli_stmt_close($stmt);
}
// echo user details
echo $details;
}
?>
答案 1 :(得分:0)
您的代码中存在多个错误
首先,您应该使用data: {u: usr},
而不是data: "u=":usr,
$(document).ready(function() {
$.ajax({
type: "GET",
url: "fetch.php",
data: {u: usr},
success: function(d) {
$("#detail").html(d);
}
});
});
在fetch.php
文件中秒,您应该获得参数$_GET['u']
而不是$_GET['usr']
<?php
// connect to db
include 'db.php';
if (isset($_GET['u'])) {
$user_query = "SELECT details FROM users_det WHERE name = ?";
if ($stmt = mysqli_prepare($db_var, $user_query)) {
mysqli_stmt_bind_param($stmt, "s", $_GET['u']); //also change `usr` in this line
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $details);
while (mysqli_stmt_fetch($stmt)) {
// fetch results
}
// close statement
mysqli_stmt_close($stmt);
}
// echo user details
echo $details;
}
?>
对于调试,您可以在ajax成功响应中使用console.log(d)