加载PHP页面内容而不刷新页面

时间:2013-10-24 10:30:18

标签: php jquery ajax

我正在尝试在用户点击链接时从PHP页面加载内容:

用户可以单击链接以获取文件中的AJAX数据:message.php

我目前在message.php

中有此代码
            $('#pmid<?php echo $convoData['id']; ?>').click(function(){
                  $.ajax({
                    type:"GET", //this is the default
                    url: "/index.php?i=pm&p=rr",
                    data: {id:"<?php echo $convoData['id']; ?>"}
                  })
                  .done(function( stuff ) {
                  $( "#name" ).html( stuff ); 
                  $( "#post" ).html( otherstuff );
                  $( "")
                  });
              });

HTML:

    Chat with <span id="name"></span> //The $name should be added to here
    <ul id="post"></ul> //The $post should be added to here

AJAX从中获取数据的页面名为:get.php,它看起来像这样:

    $id = $_GET['id'];
    $get=mysql_query("SELECT * FROM private_messages WHERE id='$id'");
    $getData=mysql_fetch_assoc($get);


    //Set the variables that needs to be send back to the other page.
    $getUser=$user->getUserData($getData['sender_id']);


    $name=$getUser['username'];
    $post = '
    <li>
      <img width="30" height="30" src="images/avatar-male.jpg">
      <div class="bubble">
        <a class="user-name" href="">'.$name.'</a>
        <p class="message">
          '.$getData['subject'].'
        </p>
        <p class="time">

        </p>
      </div>
    </li>
    ';
echo $name;
echo $post;

因此,问题是目前所有数据都只是在#name

中打印出来

如何执行此操作$name将打印在#name$post #post中?

3 个答案:

答案 0 :(得分:0)

我使用json传递两个变量:

JS:

$('#pmid<?php echo $convoData['id']; ?>').click(function(){
                  $.ajax({
                    type:"GET", //this is the default
                    url: "/index.php?i=pm&p=rr",
                    data: {id:"<?php echo $convoData['id']; ?>",},
                    dataType: 'json'
                  })
                  .done(function( stuff ) {
                  $( "#name" ).html( stuff[0] ); 
                  $( "#post" ).html( stuff[1] );
                  $( "")
                  });
              });

PHP:

echo json_encode(array($name,$post));

答案 1 :(得分:0)

将输出作为带有两个键的json编码数组返回,并在响应中显示基于此类键的值

在你的php中

$arrRet = array();
$arrRet['name'] = $name;
$arrRet['post'] = $post;
echo json_encode($arrRet); 
die();

在ajax中

$.ajax({
     type:"GET",
     url: "/index.php?i=pm&p=rr",
     dataType:'json',
     data: {id:"<?php echo $convoData['id']; ?>"},
     success : function(res){
       if(res){
        $( "#name").html(res.name); 
        $( "#post").html(res.post);
       }
     }
});

答案 2 :(得分:0)

尝试像这样返回:

$output = array();
$output['name'] = $name;
$output['post'] = $post;
$output = json_encode($output);
echo json_encode($output); exit;

然后在js中返回尝试:

function(data){
     $( "#name" ).html( data.name ); 
     $( "#post" ).html( data.post );
}