Ajax Servlet问题 [英] Ajax Servlet Issue
问题描述
这里的问题是,如果我进行搜索,则返回结果,然后在完成该过程后不久,该页面将更改为带有json原始数据的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.
此JSP提交表单
<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>
这是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);
这是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);}
}
我试图消除:action="./urllinks" method="GET"
,但是没有数据
I tried to eliminate : action="./urllinks" method="GET"
but then no data
推荐答案
您似乎尚未阻止默认的非ajax表单提交触发.
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
}
);
}
);
实际上在下面有一个Jquery插件,您可以在其中将所有样板简化为几行js.
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/
这篇关于Ajax Servlet问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!