在jQuery中的GET请求中使用发送按钮

Using a send button in a GET request in jQuery

本文关键字:按钮 jQuery 中的 GET 请求      更新时间:2024-02-29

我使用jQuery向服务器发送请求,然后呈现结果。然而,现在我想使用一个按钮,这样只有在点击发送按钮后才能发送请求,而不是像我以前的代码那样使用无法控制的"onkeyup";因为我想在完成输入请求后发送请求,而不是在之前发送。

         <script>
       function Search(query_text)
        {
        $.get( "http://localhost:9000?query="+query_text, function( data ) {
                 $('"#div2'").empty()
                 ..............
                 $('"#div2'").append("</table>")
        }, "json")
    .fail(function() {
           $("#rep")
               .append('<br/><p style="color:red">Oops! Error with XMLHttpRequest</p>')
        });
        ;
        }   
        </script>

这是调用jQuery函数的输入:

  <input id="queryText" type="text" onkeyup="Search($(this).val())" /><br>

我试着添加一个简单的按钮,然后像这样调用jQuery函数,但它没有起作用,因为页面重新加载,我没有得到我需要的结果:

        <form class="form-inline">
        <div class="form-group">
        <input type="text" class="form-control" id="queryText" placeholder="Your text">
        </div>
        <button type="submit" class="btn btn-primary" onclick="Search($('#queryText').val())">Find courses</button>
        </form>

我不知道是否有一种方法可以继续使用GET请求,而不是使用表单并在那时发送POST请求。

提前谢谢!

在jQuery选择器中更正使用queryTexte而非queryTextid,而不是使用双引号,如图所示:-

<button type="button" class="btn btn-primary" onclick="Search($('#queryTexte').val())">Search</button>

不要使用type=submit按钮,将其设为type=button,如上所示。

我会这样做,以保持JS和HTML分离,并避免引用问题:

$("button").on("click", function(){
    Search($("#queryTexte").val());
});

如果您的脚本是在DOM元素之前加载的,那么像这样包装它以等待DOM准备好:

$(function){
    $("button").on("click", function(){
        Search($("#queryTexte").val());
    });
});

HTML:

<input id="queryTexte" type="text" /><br>

jQuery:

<script>
jQuery(document).ready(function($){
    $('.btn-primary').click(function(){
    var query_text = $('#queryTexte').val();
            $.get( "http://localhost:9000?query="+query_text, function( data ) {
                     $('#div2').empty();
                     ..............
                     $('#div2').append("</table>");
            }, "json")
        .fail(function() {
               $("#rep")
                   .append('<br/><p style="color:red">Oops! Error with XMLHttpRequest</p>')
            });
      });
});
</script>