输入后,AJAX请求并附加到列表中

时间:2014-06-19 01:17:51

标签: php ajax

当用户按 Enter 键时,我正在尝试通过ajax向PHP PAGE发送和输入文本值。

这个想法是:

  • 用户在INPUT TEXT上编写代码
  • 用户按 Enter
  • AJAX调用ACTION.PHP并传递INPUT TEXT的值
  • ACTION.PHP返回和HTML内容(通过数据库)
  • HTML内容添加在通过ajax调用ACTION.PHP的页面上。

其他问题是我想在列表中添加一个或多个项目而不是OVERWRITE ...

我有这段代码:

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

1 个答案:

答案 0 :(得分:1)

绑定keydown事件,并测试keyCode以查看它是否为 Enter 键。然后,您需要使用this.value选项将data:传递给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>元素附加到此列表中。