我有一个从数据库返回数据的API。
这是我的表格
<form action="<c:url value="/getCandidateDetails"/>" method="post">
<div class="form-group">
<label for="masterId">Master Id:</label><br/>
<input type="text" id="masterId"
path="studentmasterid" name="studentmasterid" class="form-control">
</div>
<input type="hidden" value="Pending" name="paymentStatus"/>
<button class="btn btn-primary" type="submit" id="search">Search</button>
</form>
控制器部分看起来像这样。
@RequestMapping(value = "/getCandidateDetails", method = RequestMethod.POST)
public @ResponseBody List<CandidateappearagainstadvtcodeEntity> getCandidateDetails
(Model model, @RequestParam("studentmasterid") String studentmasterid,
@RequestParam("paymentStatus")String paymentstatus){
List<CandidateappearagainstadvtcodeEntity> candidates=
candidateappearagainstadvtcodeEntityRepository.findByStudentmasteridAndPaymentstatus
(studentmasterid,paymentstatus);
return candidates;
}
它抛出了json
[{"id":393,"advertisementcode":"15206-15206/2071-
72","ageonlastdateday":0,"ageonlastdatemonth":0,"ageonlastdateyear":0,
"applicationnumber":"38483928614","attendancestatus":"Pending",
"candidatefirstname":"RAJENDRA","dateofbirthinnepali":null,
"interviewmarksallocationstatus":null,"interviewscheduledstatus":null,
"mothername":"धनराज्य लक्ष्मी पाण्डे",
"candidatenameinnepali":"राजेन्द्रपाण्डे",
"marksobtained":0.0,"optionalpaperid":"NA","panelname":null,
"paymentstatus":"Pending","studentmasterid":"1161"}]
您可以看到我的表单发送了两个参数studentmasterid和付款详细信息。 每当我点击搜索按钮时,它应该使用post方法点击api,获取返回的数据并在jsp页面上查看它。我怎么能用ajax来做呢?
答案 0 :(得分:0)
您的表单目前正在进行HTML POST。相反,你打算使用AJAX。这是你在jQuery中的方法:
HTML
<form id="myform" action="<c:url value="/getCandidateDetails"/>" method="post">
<div class="form-group">
<label for="masterId">Master Id:</label><br/>
<input type="text" id="masterId"
path="studentmasterid" name="studentmasterid" class="form-control">
</div>
<input type="hidden" value="Pending" name="paymentStatus"/>
<button class="btn btn-primary" type="submit" id="search">Search</button>
</form>
的Javascript
$("#myform").submit(function(submitEvent) {
submitEvent.preventDefault(); //Prevents HTML POST
var items = $(this).find("[name]"); //Finds all the named items in the form
//Builds the data object
var data = {};
for (var index in items) {
data[items[index].prop("name")] = items[index].val();
}
$.ajax({
url: $(this).prop("action"),
data: data,
method: "POST"
}).done(function(responseData) {
//Do something with the response you have received from the server.
});
});
如果你更喜欢简单的Javascript,你可以通过向onsubmit
的Javascript对象添加form
处理程序来实现相同的目标
<form onsubmit="event.preventDefault(); sendAJAX();">
您需要定义sendAJAX
来发送AJAX in plain Javascript。