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条)

报告相同问题?