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/

    评论

报告相同问题?

悬赏问题

  • ¥15 onlyoffice编辑完后立即下载,下载的不是最新编辑的文档
  • ¥15 求caverdock使用教程
  • ¥15 Coze智能助手搭建过程中的问题请教
  • ¥15 12864只亮屏 不显示汉字
  • ¥20 三极管1000倍放大电路
  • ¥15 vscode报错如何解决
  • ¥15 前端vue CryptoJS Aes CBC加密后端java解密
  • ¥15 python随机森林对两个excel表格读取,shap报错
  • ¥15 基于STM32心率血氧监测(OLED显示)相关代码运行成功后烧录成功OLED显示屏不显示的原因是什么
  • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。