[英]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.