2014-06-19 26 views
0

我想,當用戶按通過AJAX發送和輸入文本值到一個PHP頁面輸入鍵。AJAX請求並追加後按列出進入

的理念是:

  • 用戶編寫代碼上輸入文本
  • 用戶按輸入
  • AJAX調用action.php的和通過輸入文本
  • 行動的價值.PHP收益和HTML內容(通過數據庫)
  • HTML內容誰通過AJAX稱爲action.php的頁面上添加。

另一個問題是,我想補充的1個或多個項目的列表上,而不是覆蓋它...

我有這樣的代碼:

<script type="text/javascript"> 

$(document).ready(function() { 

    $(".code").bind("enterKey",function(e){     

     $.ajax({ //create an ajax request to load_page.php 
     type: "GET", 
     url: "ACTION.php",    
     dataType: "html", //expect html to be returned     
     success: function(response){      
      $("#responsecontainer").html(response); 
      //alert(response); 
     } 

    }); 
}); 
}); 

</script> 

<input name="code" class="code" type="text" name="code" /> 

<div id="responsecontainer"></div> 

和我的行動是PHP像這樣:

<?php 
/* connection to database code is here.. just remove because isn't necessary */ 

/* Query code is here too */ 

echo $line['nome']; 

?> 

正如你所看到的,$(".code").bind("enterKey",function(e){不工作,我不知道該怎麼DIV #responsecontainer更改爲LIST <ul><li></li></ul>並添加新<li>每個請求。

+4

沒有'enterKey'事件。使用'keyup'事件,並測試關鍵代碼以查看它是否是'Return'鍵。 – Barmar

+4

你錯過了'數據:'選項阿賈克斯'$()'通過將輸入的值。 – Barmar

回答

1

綁定​​事件,並測試keyCode以查看它是否爲輸入鍵。然後,你需要使用data:選項傳遞this.value PHP腳本。

$(function() { 
    $(".code").keydown(function(e) { 
     if (e.keyCode == 13) { 
      $.ajax({ 
       type: "GET", 
       url: "ACTION.php", 
       data: { code: this.value }, 
       dataType: "HTML", 
       success: function(response) { 
        $("#responsecontainer ul").append($("<li>", { html: response })); 
      }); 
     } 
    }); 
}); 

您shold你的HTML更改爲:

<div id="responsecontainer"> 
<ul></ul> 
</div> 

然後上面的AJAX代碼將能夠追加<li>元素到此列表。