2013-08-24 44 views
0

什麼是最常接受的方式來檢索數據而無需重新加載,我看過的教程使用echo encode_json(array),本教程以下沒有使用它,而是..我認爲他選擇獲得HTML特定PHP頁面的區域。接受使用jQuery提交和檢索數據的方法ajax

的index.php

$("#button").click(function() { 
    ... some code here .... 

     $.ajax 
     ({ 
      type: "POST", 
      url: "update.php", 
      data: dataString, 
      dataType: 'html', 
      cache: false, 
      success: function(html) 
      { 
      $("#posts").prepend(html); 
      $("#posts").slideDown("slow"); 
      document.getElementById('content').value=''; 
      document.getElementById('content').focus(); 
      } 
     }); 
    }); 

成功後,我想從我的MYSQL檢索數據並將其打印在我#posts DIV。

update.php包括

  • 插入數據的MySQL
  • 選擇/檢索從MySQL數據
  • 從的mysql_query

    <?php 
        include("connect.php"); 
        if (isset($_POST['submit'])) 
        { 
        $status = $_POST['status']; //get textarea value 
        mysql_query("insert into messages (msg) values ('$status')"); 
        } 
    
        $sql = mysql_query("SELECT msg,msg_id FROM messages order by msg_id desc"); 
        $row = mysql_fetch_array($sql); 
        $msg = $row['msg']; 
        $msg_id = $row['msg_id']; 
    
    
    ?> 
    
        <!-- get this part --> 
    
        <li id="posts"> 
        id:<?php echo $msg_id; ?> 
        text: <?php echo $msg; ?> 
        </li> 
    

基本上相呼應的數據,我只是窪nt提交帖子,並顯示全部帖子無需重新加載。

+0

沒有最好的方法。這取決於你的應用程序。一個考慮因素是帶寬。發送少量數據比完全結構化的HTML片段更有效。但我不擔心,如果數據加載只是幾個K. – 2013-08-24 14:08:11

回答

0

你絕對是在正確的軌道上。 但是,您正試圖將一個id="posts"的東西插入到頁面中已有的元素上,該元素的ID不正確。 也許會讓一類的posts-container包裝DIV,然後你可以返回從PHP這樣說:

<li class="post"> 
    id:<?php echo $msg_id; ?> 
    text: <?php echo $msg; ?> 
</li> 

,並把它添加到您的網頁是這樣的:

$.ajax 
     ({ 
      type: "POST", 
      url: "update.php", 
      data: dataString, 
      dataType: 'html', 
      cache: false, 
      success: function(html) 
      { 
      $(".post-container").prepend(html); 
      $(".post-container").slideDown("slow"); 
      document.getElementById('content').value=''; 
      document.getElementById('content').focus(); 
      }, 
      //adding an error function 
      error: function(error){ 
       //do whatever you need to handle you error here 
       console.log(error); 
      } 
     }); 
+0

'成功:功能(html)'這是檢索/獲取** update.php **的HTML部分的代碼?然後將其打印在「.post-container」中? – bobbyjones

+0

是的。只要服務器端沒有錯誤,你就會調用Ajax調用的「success」函數,否則它會調用你錯過的'error'函數。我將編輯上面的內容給你一個想法。然後你可以使用返回的數據去做任何事情。 根據文檔[here](http://api.jquery.com/jQuery.ajax/),因爲你已經指定dataType爲html,所以你會在你的成功函數'「html」中得到這個:以純文本形式返回HTML;包含的腳本標籤在插入DOM時被評估。「 希望有所幫助。 –

+0

嗨,我很抱歉,如果這已經太多問。但是,我真的無法得到代碼的工作。我檢查了控制檯日誌,並沒有顯示錯誤。我根據你的文章改變了我的代碼。我的其他頁面的html不會顯示在我的索引上,通過ajax – bobbyjones