weixin_33727510 2015-05-26 19:55 采纳率: 0%
浏览 14

Ajax Servlet问题

The problem here is, if i make a search, the results are returned then shortly after the process is done, the page changes to the servlet with json raw data. I am confused here.

This JSP submits the form

<form class="col-lg-12" action="./urllinks" method="GET" id="searchform">

                        <div class="input-group"
                            style="width: 340px; text-align: center; margin: 0 auto;">
                            <input class="form-control input-lg" title="Make a wish !."
                                placeholder="Go on and search ! Don't be shy :p" type="text" id="box"
                                name="query"> <span class="input-group-btn"><button
                                    class="btn btn-lg btn-primary" id="searchresult" type="submit">Search</button></span>
                        </div>

</form>

This is the Servlet doGET

    String word = request.getParameter("query");
    List<Page> results = DynamoDbMethods.search(word);

    String reply = new Gson().toJson(results); 

    response.setContentType("text/json"); 
    response.setHeader("Cache-Control", "no-cache");
    response.getWriter().write(reply);

This is the Javascript AJAX

$('#searchform').submit(function(){
            var query = $("#box").val();

        //  alert(query);
            $.ajax({
              target:"#map", 
                dataType: "json",
                type: 'GET',
                data:{query: query},
                url: 'http://localhost:8080/path/urllinks',
                success: function(response) {
                    successCallback(response);}

          });
        });

function successCallback(responseObj){
  #This function just prints the data on a table
  #e.g 
 $.each(responseObj, function(index, element){ alert(element.title);}

}

I tried to eliminate : action="./urllinks" method="GET" but then no data

  • 写回答

1条回答 默认 最新

  • weixin_33724059 2015-05-26 23:06
    关注

    Looks like you have not prevented the default non-ajax form submit from triggering.

    Your function can take an event param and you can use this to prevent the default.

    $(document).ready(
        function () {   
            $('#searchform').submit(   
                function(event) {
                    event.preventDefault();
                    //rest of code
                }
            );
        }
    ); 
    

    There is actually a Jquery plugin at the below where you can reduce all the boilerplate to a couple of lines of js.

    http://jquery.malsup.com/form/

    评论

报告相同问题?