[英]Get Spring @RequestParam in ajax request
I'm trying to get a Java object in my javascript. 我正在尝试在JavaScript中获取Java对象。 I'm using a ajax request to get this object.
我正在使用ajax请求来获取此对象。 Here is my code :
这是我的代码:
@RequestMapping(path = "/sendSMS", method = RequestMethod.POST)
public void sendSMS(HttpServletRequest request,
HttpServletResponse response,
final ModelMap contactModel,
@RequestParam(value = "id") final String contactId) { ... }
and my ajax request : 和我的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);
}
}
}
})
The error I got in Eclipse is: 我在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)
This line is : 这行是:
Integer id = Integer.parseInt(contactId);
EDIT : It works when I hard code the id. 编辑:当我对ID进行硬编码时,它可以工作。 I just modify
url
like this : 我只是这样修改
url
:
var smsUrl = '/contacts/sendSMS?id=113';
url : smsUrl,
Now my problem is that I don't know how to get the id value dynamically. 现在我的问题是我不知道如何动态获取id值。
将url : '/contacts/sendSMS?id=' + ${param.id}
url : '/contacts/sendSMS?id=${param.id}'
更改为url : '/contacts/sendSMS?id=' + ${param.id}
${param.id}
This value comes from Spring. 该值来自Spring。 JavaScript files should be seperated from JSP files.
JavaScript文件应与JSP文件分开。 You can for example connect Spring variable to HTML tag in your JSP file like
<form>
: 例如,您可以将Spring变量连接到JSP文件中的HTML标签,例如
<form>
:
<form myattribute="${param.id}">
...
</form>
and now you can fetch this value in your JavaScript file with jQuery like this: 现在您可以使用jQuery在JavaScript文件中获取此值,如下所示:
var myId = $('form').attr('myattribute');
$.ajax({
type : 'POST',
url : '/contacts/sendSMS?id=' + myId
...
});
You can also use the data-* attribute to embed custom data in your HTML tags like: 您还可以使用data- *属性将自定义数据嵌入HTML标记中,例如:
<form data-myvariable="${param.id}">
...
</form>
and then in JS file: 然后在JS文件中:
var myId = $('form').data("myvariable");
$.ajax({
type : 'POST',
url : '/contacts/sendSMS?id=' + myId
...
});
In your AJAX call you are defining the url as a static value, while the id should be dynamic. 在AJAX调用中,您将url定义为静态值,而id应该是动态的。 Change it to:
更改为:
url : '/contacts/sendSMS?id='+${param.id},
url : '/contacts/sendSMS?id='+${param.id}
should to the magic, but as you mentioned in earlier answers to you maybe mix JavaScript and JSPs ? 应该魔术,但是正如您在前面的答案中提到的,您可能将JavaScript和JSP混合使用了?
You might want also to take a look at: Reading a JSP variable from JavaScript 您可能还想看看: 从JavaScript读取JSP变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.