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 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效