我在页面上创建了标记输入部分,并希望在用户输入标记时保存标记。
所以我试图将一个Javascript数组的字符串传递给一个弹簧控制器。
这是用于填充tagList数组的javascript。 它基本上给了我一个数组:
var taglist = [];
a[0] = hi;
a[1] = bye;
a[2] = shoe;
这是我尝试这样做的方式。
$(':submit').click(function() {
alert("array is "
+ JSON.stringify(tagList));
alert("enter ajax");
$.ajax({
type : "POST",
url : "/json/tags",
data : {
tagList : a
},
success : function(response) {
alert("good results")
},
error : function(e) {
alert('Error: ' + e);
}
});
})
列表正在填充正常,就在我尝试将此List传递给我的控制器时。
@RequestMapping(value = "/json/tags", method = RequestMethod.POST)
public String controllerMethod(@RequestParam(value="tagList[]") String[] myArray){
System.out.println(myArray);
if(myArray.length> 2){
return "good";
}else{
return "bad";
}
}
我正在关注这个使用整数数组的tutorial,但似乎无法使用String数组。
答案 0 :(得分:0)
需要使用GET而不是POST和其他一些小的改动
alert("array is " + JSON.stringify(tagList));
var methodPN = 'getTagName';
<c:url var="getTagUrl" value="/json/tags.json" />
var ajaxURL = '${getTagUrl}';
var photoid = '${photo.uploadedFile.id}';
var sendData = {
controllerMethod: methodPN,
tagList : tagList,
photoid : photoid
};
alert("enter ajax");
$.ajax({
url : ajaxURL,
data : sendData,
type : "GET",
beforeSend: function (xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success : function(response) {
alert("good results")
},
error : function(e) {
alert('Error: ' + e);
}
});
})
我更新的控制器
@RequestMapping(value = "/json/tags", method = RequestMethod.GET, params = "controllerMethod=getTagName",
produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String controllerMethod(Model model,@RequestParam(value="tagList[]", required = true) String[] myArray, @RequestParam(value="photoid", required = true) long photoid){