繁体   English   中英

在ajax请求中获取Spring @RequestParam

[英]Get Spring @RequestParam in ajax request

我正在尝试在JavaScript中获取Java对象。 我正在使用ajax请求来获取此对象。 这是我的代码:

@RequestMapping(path = "/sendSMS", method = RequestMethod.POST)
public void sendSMS(HttpServletRequest request, 
                    HttpServletResponse response, 
                    final ModelMap contactModel,
                    @RequestParam(value = "id") final String contactId) { ... }

和我的ajax请求:

var $this = $(this);
$.ajax({
    type : 'POST',
    url : '/contacts/sendSMS?id=${param.id}',
    data : $this.serialize(),
    dataType : 'json',
    success : function(json) {
        alert("success");
        $.each(json,function(index,element) {
            if (index == "message") {
                message = element;
                alert(message);
            }
        }
    }
})

我在Eclipse中遇到的错误是:

java.lang.NumberFormatException: For input string: "${param.id}"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at com.controller.contact.ContactController.sendSMS(ContactController.java:259)

这行是:

Integer id = Integer.parseInt(contactId);

编辑:当我对ID进行硬编码时,它可以工作。 我只是这样修改url

var smsUrl = '/contacts/sendSMS?id=113';
url : smsUrl,

现在我的问题是我不知道如何动态获取id值。

url : '/contacts/sendSMS?id=' + ${param.id} url : '/contacts/sendSMS?id=${param.id}'更改为url : '/contacts/sendSMS?id=' + ${param.id}

${param.id}

该值来自Spring。 JavaScript文件应与JSP文件分开。 例如,您可以将Spring变量连接到JSP文件中的HTML标签,例如<form>

<form myattribute="${param.id}">
... 
</form>

现在您可以使用jQuery在JavaScript文件中获取此值,如下所示:

var myId = $('form').attr('myattribute');

$.ajax({ 
    type : 'POST',
    url : '/contacts/sendSMS?id=' + myId 
    ...
});

您还可以使用data- *属性将自定义数据嵌入HTML标记中,例如:

 <form data-myvariable="${param.id}">
 ... 
 </form>

然后在JS文件中:

var myId = $('form').data("myvariable");

$.ajax({ 
    type : 'POST',
    url : '/contacts/sendSMS?id=' + myId 
    ...
});

在AJAX调用中,您将url定义为静态值,而id应该是动态的。 更改为:

 url : '/contacts/sendSMS?id='+${param.id},
url : '/contacts/sendSMS?id='+${param.id}

应该魔术,但是正如您在前面的答案中提到的,您可能将JavaScript和JSP混合使用了?

您可能还想看看: 从JavaScript读取JSP变量

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM