doubi9255
2016-10-10 17:44 浏览 59

如何通过ajax获取数据,将php变量传递给外部php文件?

I have 2 files, index.php and ajax.php, I am retrieving data from ajax.php to display in index.php via ajax.. I would like to pass the username to ajax.php to use in my sql statement.. How can I achieve this?

index.php -

$profile_user =$_GET['user'];

    $(document).ready(function(){
        $('.loader').hide();
        var load = 0;
        var nbr = "<?php echo $nbr;?>";
        $(window).scroll (function(){
            if($(window).scrollTop() == $(document).height() - $(window).height()){
                $('.loader').show();
                load++;
                if(load * 5 > nbr){
                    $('.messages').text("No more to see..");
                    $('.loader').hide();
                }else{

                $.post("ajax.php", {load:load},function(data){
                    $(".images").append(data);
                    $('.loader').hide();
                });
                }
            }
        });
    });

ajax.php

$profile_user =$_GET['user'];
$sql = "SELECT * FROM images WHERE  user = '$profile_user'  ORDER BY ID DESC ";

Can I pass the variable in the ajax call?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答 默认 最新

  • 已采纳
    dsqa6272 dsqa6272 2016-10-10 17:49

    Add the PHP variable in the AJAX call

    $.post("ajax.php", {
      load: load,
      user: '<?php echo $profile_user; ?>'
    },function(data){
    

    And change $_GET by $_POST in your ajax.php file, like this

    $profile_user = $_POST['user'];
    
    点赞 评论 复制链接分享
  • duanpin5168 duanpin5168 2016-10-10 17:51

    You need to POST that data:

                $.post('ajax.php', {load:load, user: '"<?php echo $_GET['user'];?>"'},function(data){
                    $('.images').append(data);
                    $('.loader').hide();
                });
    
    点赞 评论 复制链接分享
  • dousi2251 dousi2251 2016-10-10 17:52

    You can change

    $.post("ajax.php", {load:load},function(data){
                        $(".images").append(data);
                        $('.loader').hide();
                    });
    

    to

    $.post("ajax.php", {load:load, user:user},function(data){
                            $(".images").append(data);
                            $('.loader').hide();
                        });
    

    And in ajax.php after getting mysql result just encode the array in json format and echo it.

    $data = mysql_query($sql);
    echo json_encode($data);exit;
    
    点赞 评论 复制链接分享

相关推荐