javascript - 如何在不刷新页面的情况下将值从 jsp 页面发送到数据库
问题描述
我正在开发一个 spring+hibernate 网络应用程序,用于练习从俄语到英语的翻译技巧。
在我的一个 jsp 页面中,我从数据库中检索所有问题并将它们放入包含以下列的表中:俄语文本、用户翻译字段、检查结果按钮。
目标是在不刷新页面的情况下将用户的输入保存到数据库中。我该怎么做?我尝试了几个选项,但没有一个对我有用。
我在我的项目中使用了Send javascript variables to spring controller的解决方案,但什么也没发生。
“firstPage.jsp”的一部分(控制器中的“/first”路径):
<head>
<title>Title</title>
<script>
function searchViaAjax(id) {
var tempId = id;
alert("Start");
$.ajax({
type : "POST",
url : "./search/api/getSearchResult",
data : {id:tempId},
timeout : 100000,
success : function(id) {
alert("success");
console.log("SUCCESS: ", id);
display(id);
alert(response);
},
error : function(e) {
alert("error");
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
alert("done");
console.log("DONE");
}
});
}
</script>
</head>
<body>
<button onclick="searchViaAjax(1)">Simple button</button>
</body>
控制器类:
@Controller
public class DemoController {
@RequestMapping("/first")
public String getFirst(){
return "firstPage";
}
@ResponseBody
@RequestMapping(value = "/search/api/getSearchResult", method=RequestMethod.POST)
public String getSearchResultViaAjax(@RequestParam("id") Integer id) {
System.out.println("come to ajax"+ id);
return "hello";
}
}
“开始”消息会被打印,但其他消息searchViaAjax()
不会。并且控制器方法没有启动。
解决方案
您可以传入id
控制器,因为它在您的“id”中没有问题,您也可以跳过@RequestParam
.
@ResponseBody
@RequestMapping(value = "/search/api/getSearchResult")
public String getSearchResultViaAjax(@RequestParam("id") integer id) {
System.out.println("come to ajax"+ id);
return "hello";
}
指定方法类型
@RequestMapping(value = "/search/api/getSearchResult", methodType=RequestMethod.POST)
使用包装器而不是原始的也是一个好习惯
@RequestParam("tempId") Integer id
问题出在您的 ajaxurl
属性中。
它应该是url : "./search/api/getSearchResult",
根本原因:
当你即将点击你的控制器时,它会像这样构造 url
http://localhost:8080/search/api/getSearchResult
因此此类资源不可用,并导致 404 not found 错误。
实际上,网址应该是
http://localhost:8080/contextroot/search/api/getSearchResult
这里contextroot
指的是您的项目名称。
现在,如果您点击 url ./search/api/getSearchResult
,则./
引用基本 url,localhost:8080/contextroot
即整个 url 将被正确构造。
我想建议你在 JavaScript 中创建全局变量,baseUri
然后赋值给./
它。
<script>
var baseUri="./";
</script>
在你的 AJAX 中它变成
url : baseUri+"search/api/getSearchResult",
希望这会有所帮助
推荐阅读
- r - 使用 R 的 pool 包重新连接到 PostgreSQL 数据库
- android - 如何以编程方式在运行 android 的设备上安装 SSL CA 证书?
- php - 使用 PHP 从 db-ip.com 解码 api 的 JSON
- raspberry-pi - 修复 Raspberry Pi 3 上的升级错误
- pyqt5 - Pyinstaller 不适用于本地文件
- c# - 如何在 MVC 中重载控制器方法?
- sql - 无法在 SQL Server 中使用 LAG 函数检索数据
- c - 从 'int*' 到 'unsigned int*' 的无效转换 [-fpermissive]
- android - 在 Android Recyclerview 中处理多个按钮单击并将响应存储在 Array 或 ArrayList 中
- php - 点击登录按钮后页面没有变化?