[英]How to get parametr in response from spring? (rest Javascript)
我在向 html 返回錯誤時遇到問題。 所以,我有帶有“sql解釋器”的網絡應用程序。
HTML
<button type="submit" onclick="executeSQL('interpreterSQL')">
<i class="fas fa-bolt"></i>
</button>
<textarea id="interpreterSQL" placeholder="❔❔❔"></textarea>
在解釋器中輸入查詢后,我在 javascript 中運行 POST 並拍攝到 spring:
在 JavaScript 中發布
function executeSQL(interpreterSQL) {
var tmp = document.getElementById(interpreterSQL).value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
var response = xhttp.responseText;
console.log("ok"+response);
}
};
xhttp.open("POST", "/user/executeSQL", true);
xhttp.send(tmp);
}
之后,我在我的服務中處理查詢並將消息返回到我的控制器中的 POST:
控制器(Spring 中的 POST)
@PostMapping(path = { "/user/executeSQL" })
public ModelAndView executeSQL(@RequestBody String tmp) {
String[] split = tmp.replace("\n", "").replace("\t", "").split(";");
String feedback = databaseTableService.executeSQL(split);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("successMessage", feedback);
modelAndView.setViewName("/user/interpreterSQL");
return modelAndView;
}
用於執行本機查詢的服務
public String executeSQL(String[] split){
SessionFactory hibernateFactory = someService.getHibernateFactory();
Session session = hibernateFactory.openSession();
String message = null;
for (int i = 0; i < split.length; i++) {
try{
String query = split[i];
session.doWork(connection -> connection.prepareStatement(query).execute());
message = "Success";
}
catch(Exception e){
message = ((SQLGrammarException) e).getSQLException().getMessage();
}
}
session.close();
return message;
}
所以最后我們在我的控制器中,它准備好返回值,我們有消息,其中包含有關 sql 異常的信息。 我們在那里:
這是我的問題:如何獲得可變的“反饋”作為回應?
但是“var response = xhttp.responseText”正在返回我所有的 HTML 代碼。 我只需要控制器的參數“反饋”。 伙計們有人可以幫忙嗎? :(我不知道如何返回該參數並在javascript中處理它...
也許您可以更改您的 Controler 方法以在ModelAndView
上返回 JSON 響應
@PostMapping(path = { "/user/executeSQL" })
public ResponseEntity<Object> executeSQL(@RequestBody String tmp) {
String[] split = tmp.replace("\n", "").replace("\t", "").split(";");
Map<String,String> response = new HashMap<String, String>();
response.put("feedback", databaseTableService.executeSQL(split));
return new ResponseEntity<>( response , HttpStatus.OK);
}
現在您應該能夠看到狀態
var response = xhttp.responseText;
console.log("ok"+response);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.