首页 > 解决方案 > 如何在不刷新页面的情况下将值从 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()不会。并且控制器方法没有启动。

标签: javascriptjqueryajaxhibernatespring-mvc

解决方案


您可以传入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",

希望这会有所帮助


推荐阅读