Spring MVC + jQuery AJAX 向後臺傳遞數據的幾種方式

要理解這篇文章,先看Spring MVC 接收請求參數的註解和響應註解

要使用$.ajax({})方法 需要再maven項目下添加jquery依賴

否則會報錯  Uncaught ReferenceError: $ is not defined 就是因爲項目中沒有jQuery依賴

		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>jquery</artifactId>
			<version>3.3.1-2</version>
		</dependency>

 然後再jsp文件添加如下代碼 web-demo-test是我的項目名稱

<script src="/web-demo-test/webjars/jquery/3.3.1-2/jquery.js"></script>
<script src="/web-demo-test/webjars/jquery/3.3.1-2/jquery.min.js"></script>

1.通過ajax的url路徑 傳遞參數 + 後臺用Spring @PathVariable註解 接收參數

  • 1.1 jsp頁面 
<script>
	function test() {
		$.ajax({
			async : false,
			cache : false,
			type : 'POST',
			url : '/web-demo-test/student/add/' +"lisi"+ '/' +33,//(1)請求的action路徑,可以傳遞參數到後臺
			error : function() {
				alert('請求失敗 ');
			},
			success : function(data) {
				alert(data);
			}
		});
	}
</script>
  • 1.2 java 控制器方法 通過Spring 註解 @PathVariable() 接收參數,可以接收基本類型
package com.mx.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/student")
public class StudentController {

	/* 接收url中傳來的參數@PathVariable("name") String name,可以接收基本類型 */
	@RequestMapping(value = "/add/{name}/{age}", method = RequestMethod.POST)
	@ResponseBody
	public void addStudent(@PathVariable("name") String name, @PathVariable("age") Long age) {
		System.out.println(name);
		System.out.println(age);

	}
}

2.通過 ajax的data屬性 傳遞參數 + Spring @RequestParam()註解 接收參數(@RequestParam()註解可以省略

  • 2.2 前臺 jsp頁面
<script>
function submitAjax(){
	
	var postData = { //(2)傳遞參數到後臺,注意後臺接收方式 
			"name" : "zhangsan",
			"age" : 24,
			"ids" : "254,249,248"
		}
		/**重點:ajax的type,url,dataType,data屬性*/
		$.ajax({
			async : false,
			cache : false,
			type : 'POST',
			url : '/web-demo-test/student/add',
			dataType : "json",
			data : postData,
			error : function() {
				alert('請求失敗 ');
			},
			success : function(data) {
				alert(data);
			}

		});
	}
</script>
  • 2.2 java 控制器方法 通過Spring 註解 @RequestParam() 接收參數,可以接收基本類型

這種方式可以接收 各種數據類型,比如String Long 數組 (前臺是字符串,後臺是數組接收根據逗號把字符串分割成數組 看參數ids)

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/student")
public class StudentController {

 
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public void addStudent(@RequestParam("name") String name, @RequestParam("age") Long age,
			@RequestParam("ids") Long[] ids) {
		System.out.println(name);
		System.out.println(age);
		for (int i = 0; i < ids.length; i++) {
			System.out.println(ids[i]);
		}

	}
}
  • 2.3 如果ajax 是通過ajax data屬性傳遞參數,@RequestParam()註解可以省略保持方法參數名和ajax傳過來的data key值一致
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/student")
public class StudentController {

 
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public void addStudent(String name, Integer age, Long[] ids) {
		System.out.println(name);
		System.out.println(age);
		for (int i = 0; i < ids.length; i++) {
			System.out.println(ids[i]);
		}
	}
}

3.通過 ajax的data屬性 傳遞參數 + 編碼方式contentType : 'application/json',+ Spring @RequestBody()註解 接收參數

  • Http請求 傳遞參數的幾種編碼方式(content-type):默認的application/x-www-form-urlcoded;application/json;application/xml
  • Spring的 @requestBody註解常用來處理 application/json類型,
  • 如果要在在maven項目添加如下依賴,使得項目可以支持application/json編碼方式
		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.9.0</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.9.0</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.9.0</version>
		</dependency>
  •  3.1 jsp 代碼
<script>
	function test() {
		var postData = { //第一步:定義json數據
			"name" : "echo",
			"age" : 21
		}
		$.ajax({
			async : false,
			cache : false,
			type : 'POST',
			url : '/web-demo-test/student/add',
			contentType : 'application/json', //第二步:定義格式
			dataType : "json",
			data : JSON.stringify(postData),//第三步;把json轉爲String傳遞給後臺
			error : function() {
				alert('請求失敗 ');
			},
			success : function(data) {
				alert(data);
			}

		});
	}
</script>
  • 3.2 如果有Student實體類 包含name,age屬性,那麼 @requestBody Student student這種形式會將JSON字符串中的值賦予user中對應的屬性上
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mx.entity.Student;

@Controller
@RequestMapping("/student")
public class StudentController {
	 
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public String addStudent(@RequestBody Student student) {
		System.out.println(student.toString());
		return "ok";
	}

	 
}
  •  3.2 如果沒有實體類可以映射ajax傳過來的json數據  @requestBody 以map方式接收json參數
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/student")
public class StudentController1 {

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public String addStudent(@RequestBody Map<String, Object> map) {
		System.out.println("map.get(name)===" + map.get("name"));
		System.out.println("map.get(age)===" + map.get("age"));
		return "ok";
	}

}

 

原文章地址 jQuery AJAX方法 前臺往後臺傳數據 

 

 

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