SpringMVC中ajax發送jsonarray到controller的方法

<!--HTML-->
document.getElementById("Update").onclick = function UpdateById(){
			var array = [];
        	for (var i=1;i<=4;i++)
    		{            	        	
        		var info= {};
        		info.id = $("#id"+(i)).val();
        		info.name= $("#name"+(i)).val();
        		array.push(info);
        	}
        	console.log(JSON.stringify(array));
			$.ajax({	// header一定要加,否則會報415錯誤
				headers: {
	                'Accept': 'application/json',
	                'Content-Type': 'application/json'
	            },
    	        url:"${pageContext.request.contextPath}/info/update",
    	        type:"post",
    	        data:JSON.stringify(array),// 格式轉換一定要加
    	        dataType:"json",
    	        success: function(data) {
    	        	console.log(data);	        
    	        },
    	        error: function(XMLHttpRequest, textStatus, errorThrown) {
    	            alert(XMLHttpRequest.status);
    	            alert(XMLHttpRequest.readyState);
    	            alert(textStatus);
    	        },
    	    })
        };
	@RequestMapping(value = "update",method = RequestMethod.POST)
	@ResponseBody
	// 這裏List的類型只能用JSONObject,用其他的,編譯能通過,但是在實際應用中會報錯,說不能強轉。
	public boolean UpdateById(@RequestBody List<JSONObject> is) {
		System.out.println(is);	
		for(int i=0;i<is.size();i++){		    
		   	Info info = new Info();
		   	
			info.setId(ps.get(i).getInteger("id"));
			info.setName(ps.get(i).getString("name"));

			parentInfoService.UpdateById(p);
		}
		
		return true;
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章