2017-06-07 79 views
0

我有一個從數據庫返回數據的API。如何獲取post 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

您的表單當前執行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處理器的form「 s的Javascript對象

<form onsubmit="event.preventDefault(); sendAJAX();"> 

你需要d efine sendAJAX發送您的AJAX in plain Javascript