drkjzk3359 2011-10-18 11:35
浏览 36
已采纳

jQuery AJAX JSON问题

On the first page I have this function:

 <script>
function update() {
  $("#notice_div").html('Loading..'); 


  $.ajax({
    type: 'GET',
    dataType: 'json',
    data: latestid,
    url: '2includejson.php?lastid='+ latestid + '',
    timeout: 4000,
    success: function(data) {


      $("#cont_div").html(data);
      $("#cont_div").clone().prependTo($("#newdiv")); 
      $("#notice_div").html(''); 
      $("#cont_div").html('');
      window.setTimeout(update, 4000);

    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      $("#notice_div").html('Timeout contacting server..');
      window.setTimeout(update, 60000);
    }
});
}
$(document).ready(function() {
    update();

}); 
</script>

And some php.

The included file:

    <? 
     header("Content-Type: application/json", true);

    $la = $_GET['lastid'];  
    include ("../../setup.php");

    $jsonArray[] = array();

      $count = 1; // first message is the newest on load
      $get = $DB->query("SELECT * FROM board WHERE id>'$la' ORDER BY id DESC LIMIT 5", __FILE__, __LINE__);
    while ($msg = $DB->fetch_array($get))
    {   

  if($count == 1){ 
  $latestid = $msg['id']; // newest message - this I need to pass to the other page
  }
  $count++; 

    $jsonArray = "$msg[msg]";
    }
    echo json_encode($jsonArray);
    ?>

I'm just trying to learn how to use ajax and jquery.

As you see, I pass latestid as js variable through the URL url: '2includejson.php?lastid='+ latestid + '',

I need to renew/post pack a newer value from the included page but I have no idea how to do so. Before using json I could just overwrite it with javascript, but now I don't know... The newer value will then be posted again as latestid.

  • 写回答

4条回答 默认 最新

  • doupeizheng3918 2011-10-18 11:44
    关注

    You can declare the array without []:

    $jsonArray = array();
    

    Also you should then append the data to the array instead of making a string:

    $jsonArray[] = $msg['msg'];
    

    And in the end:

    $jsonArray['latestid'] = $latestid;
    

    Then in JavaScript, you should declare latestid:

    var latestid;
    

    And inside the ajax function, you should just pass the data as an object, and not twice like you're doing now. And just replace latestid there, which has been returned in JSON format:

    ...
    data: {lastid: latestid},
    url: '2includejson.php',
    timeout: 4000,
    success: function(data) {
        latestid = data.latestid; // update latestid
        ...
    }
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀