嗨,我现在有一个JS文件被调用来用动态数据填充我的html页面。我的JS文件调用一个PHP文件来从我的sqldb中获取内容,我的PHP文件echos json_encode从sqldb中获得的内容,然后用于填充html页面。
我的问题是,这取决于网址里的内容?user=Bob,我希望我的js文件调用php文件来搜索Bob。现在它搜索当前用户,如果?未指定user=xxxx。$GET['user']似乎总是null,因此它没有被传递,因为我怀疑JS文件起到了中间人的作用。以下是我的代码片段:
我的URL: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);
}
您需要在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
我相信你想做一些类似的事情
$(document).ready(function(){
$.ajax({
type: 'GET',
url: 'php/retrieve-db.php',
data: <?php echo json_encode($_GET); ?>,
dataType: 'json',
....
编辑:
感谢@Brad和@Ashwin Musjija的指出。我太快地专注于答案,以至于忽略了可能的非持久性XSS攻击。