您好我目前正在调用JS文件来填充带有动态数据的html页面。我的JS文件调用PHP文件从我的sqldb和我的PHP文件中获取东西echos json_encode从sqldb获取的东西,而sqldb又用于填充html页面。
我的问题是,根据url中的内容,即?user = Bob,我希望我的js文件调用php文件来搜索Bob。现在它搜索当前用户if?user = xxxx未指定。似乎$ GET ['user']总是为null,因此它没有被传递,因为我怀疑JS文件是作为中间人工作的。这是我的代码片段:
我的网址: www.website.com/index.php?user=Bob
我的HTML代码
<script type="text/javascript" src="js/get-data.js"></script>
我的JavaScript
$(document).ready(function(){
$.ajax({
type: 'GET',
url: 'php/retrieve-db.php',
dataType: 'json',
success: function(response){
var name = response[0];
var location = response[1];
$('#name').html(name);
$('#location').val(location);
}
});
});
我的PHP代码
$id;
if (isset($_GET["user"]))
{
$id = $_GET["user"];
}
else
{
$id = $_SESSION['loggedInUser'];
}
$query = "SELECT * FROM Persons WHERE User = '$user'";
if($result = mysqli_query($sqlconnection,$query))
{
$row = mysqli_fetch_row($result);
echo json_encode($row);
}
答案 0 :(得分:1)
您需要在ajax调用中指定data
属性。
$.ajax({
type: 'GET',
data: $("#myForm").serialize(), //for example. You can change this to something relevant.
/*rest of the code*/
});
这样做是准备一份包含适当数据的GET请求,例如http://path/to/backend/?key1=value1&key2=value2
答案 1 :(得分:-1)
我相信你想做这样的事情
$(document).ready(function(){
$.ajax({
type: 'GET',
url: 'php/retrieve-db.php',
data: <?php echo json_encode($_GET); ?>,
dataType: 'json',
....
修改强>
感谢@Brad和@Ashwin Musjija指出。我过于专注于回答,忽略了可能的非持久性XSS攻击。