按键上的AJAX?

时间:2014-05-16 12:58:05

标签: php jquery ajax

所以我是AJAX的新手,所以我想知道是否有人可以提供帮助。

我想得到这个,SQL命令在onkeyup上激活:

SELECT * FROM commands WHERE tag=$_POST['search_input']

这是我目前的表格代码:

<form method="post">
    <input class="search_input" type="text" name="search_input" placeholder="Search..." onkeyup="suggest()" autocomplete="off"  />
</form>

当前的jQuery:

$(document).ready(function() {
    $('.search_input').keypress(function(event) {
        if (event.keyCode == 13) {
            event.preventDefault();
        }
    });
    function handleKeyPress(e,form){
        var key=e.keyCode || e.which;
        if (key==13){
            form.submit();
            return false;
        }
    }
});

函数suggest()就是我喜欢你的帮助。要在按键上发送上述命令。

2 个答案:

答案 0 :(得分:0)

使用$.post()。你有这里的例子http://api.jquery.com/jquery.post/

基本结构是

$.post(url(string), data(object), function(response){ /* do something */ });

输入之间的延迟非常好,因此不会不断向服务器发送请求。你可能还想使用keyup而不是keypress,测试它,你就会明白为什么。

答案 1 :(得分:0)

我建议使用......

HTML

<form method="post">
    <input class="search_input" type="text" name="search_input" placeholder="Search..." autocomplete="off"/>
</form>

JS

// shorthand for document ready
$(function(){
    var $input = $('.search_input');

    // using on-function (see jQuery Docs)
    // bind event instead of using on-attribute (nicer)
    // bind input event instead of keyup, because it will fire on paste too
    $input.on('input', function(evt){
        $.ajax({
            // maybe use GET?
            type: 'POST',
            url: '/yourQueryPath',
            // assign the input value to the needed query parameter
            data: {'search_string': $input.val()},
            success: function(response){
                // whatever you want to to with your response
            }
        )};
    });
});

另外一个提示:永远不要像SQL那样使用未经过滤的用户输入(MySQL-Injection)! 例如。如果您使用PHP,请使用filter_input()和mysql_real_escape_string()或simliar。

相关问题