dongzhi6927 2013-08-03 04:54
浏览 75
已采纳

将GET变量从URL传递到.js,从.js传递到.php

Hi I currently have a JS file being called to populate my html page with dynamic data. My JS file calls a PHP file to fetch stuff from my sqldb and my PHP file echos json_encode the stuff it got from the sqldb, which in turn is used to populate the html page.

My problem is that depending on what's in the url ie ?user=Bob, I want my js file to call the php file to search for Bob. Right now it searches for current user if ?user=xxxx is not specified. It seems the $GET['user'] is always null, thus it's not being passed because I suspect the JS file working as a middleman. Here are my code snippets:

My URL: www.website.com/index.php?user=Bob

My HTML Code

<script type="text/javascript" src="js/get-data.js"></script>

My 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);
            }
    });
});

My PHP Code

$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);
}
  • 写回答

2条回答 默认 最新

  • duanfeng3879 2013-08-03 04:58
    关注

    I believe you want to do something like this

    $(document).ready(function(){
        $.ajax({
            type: 'GET',
            url: 'php/retrieve-db.php',
            data: <?php echo json_encode($_GET); ?>,
            dataType: 'json',
    ....
    

    EDIT:
    Thanks @Brad and @Ashwin Musjija for pointing out. I was focusing on answer too quickly that I overlook the possible non persistent XSS attack.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系