当用户按进入键时,我试图通过ajax发送和输入文本值到PHP页面。
思路是:
- 用户在INPUT TEXT上写代码
- 用户按输入
- AJAX调用ACTION.PHP并传递INPUT TEXT 的值
- ACTION.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>
AND MY ACTION 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 # responsectainer更改为LIST <ul><li></li></ul>
,并为每个请求添加新的<li>
。
绑定keydown
事件,并测试keyCode以查看它是否是Enter键。然后,您需要使用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 }));
});
}
});
});
你应该把你的HTML改成:
<div id="responsecontainer">
<ul></ul>
</div>
然后上面的AJAX代码将能够将<li>
元素添加到该列表中。