再谈Jquery Ajax方法传递到action

news/2024/7/11 1:21:46 标签: jquery, Ajax, action

之前写过一篇文章 Jquery Ajax方法传值到action,本文是对该文的补充。

假设 controller中的方法是如下: 

 
  1. public ActionResult ReadPerson(PersonModel model)  
  2.         {  
  3.             string s = model.ToString();  
  4.             return Content(s);  
  5.         } 
  6. public ActionResult ReadPersons(List<PersonModel> model)  
  7.         {  
  8.             string result = "";  
  9.             if (model == null) return Content(result);  
  10.             foreach (var s in model)  
  11.             {  
  12.                 result += s.ToString();  
  13.                 result += "-------------";  
  14.             } 
  15.             return Content(result);  
  16.         } 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

 其中PersonModel定义如下: 

 
  1. public class PersonModel  
  2.     {  
  3.         public int id  
  4.         {  
  5.             set;  
  6.             get;  
  7.         }  
  8.         public string name  
  9.         {  
  10.             set;  
  11.             get;  
  12.         } 
  13.         public int age  
  14.         {  
  15.             set;  
  16.             get;  
  17.         } 
  18.         public bool gender  
  19.         {  
  20.             set;  
  21.             get;  
  22.         }  
  23.         public string city  
  24.         {  
  25.             set;  
  26.             get;  
  27.         } 
  28.         public override string ToString()  
  29.         {  
  30.             string s = string.Format(@"id:{0}  
  31. name:{1}  
  32. age:{2}  
  33. gender:{3}  
  34. city:{4}  
  35. ", id, name, age, gender, city);  
  36.             return s;  
  37.         }  
  38.     } 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.

那么controller方法分别接受单个model和一个model的List。采用通过ajax传递参数。

对于传递单个参数的情况,假设js代码如下: 

 
  1. var person = {  
  2.                id: "001",  
  3.                name: "zhangsan",  
  4.                age: "20",  
  5.                gender: true,  
  6.                city: "shanghai"  
  7.            }; 
  8. var option = {  
  9.                url: '/test/ReadPerson',  
  10.                type: 'POST',  
  11. data: person,  
  12.                dataType: 'html',  
  13.                success: function (result) { alert(result); }  
  14.            };  
  15. $.ajax(option); 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

 从chrome中截图可以看到如下:

再谈Jquery <a class=Ajax方法传递到action_MVC" height="357" src="https://img-blog.csdnimg.cn/img_convert/54336ee17cd1bc3be85c2f2dcd58d067.png" />

传递的数据是一串Form数据,根据命名匹配的原则,也是可以取得数据的。

再谈Jquery <a class=Ajax方法传递到action_MVC_02" height="193" src="https://img-blog.csdnimg.cn/img_convert/1fe3fd548f74105ceaa3046d81e8c461.png" />


将option 的代码改成如下 

 
  1. var option = {  
  2.                url: '/test/ReadPerson',  
  3.                type: 'POST',  
  4.                data: JSON.stringify(person),  
  5.                dataType: 'html',  
  6.                success: function (result) { alert(result); }  
  7.            };  
  8. $.ajax(option); 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

其中JSON.stringify方法签名为 stringify ( value [ , replacer [ , space ] ] ),根据ECMA-262标准stringify 函数返回的是JSON格式的字符串。它可以有3个参数。摘抄如下:

The stringify function returns a String in JSON format representing an ECMAScript value. It can take three parameters. The first parameter is required. The value parameter is an ECMAScript value, which is usually an object or array, although it can also be a String, Boolean, Number or null. The optional replacer parameter is either a function that alters the way objects and arrays are stringified, or an array of Strings and Numbers that acts as a white list for selecting the object properties that will be stringified. The optional space parameter is a String or Number that allows the result to have white space injected into it to improve human readability.

默认的ContentType的属性值是"application/x-www-form-urlencoded"

引自 http://www.w3.org/TR/html401/interact/forms.html#adef-enctype

看请求头的截图:

再谈Jquery <a class=Ajax方法传递到action_MVC_03" height="311" src="https://img-blog.csdnimg.cn/img_convert/25c5ebacf661be3a374de26bf17b7660.png" />

因此,传递到controller的是一个json字符串,MVC根据命名匹配也是可以获得到参数的值。


将将option 的代码改成如下

 
  1. var option = {  
  2.                 url: '/test/ReadPerson',  
  3.                 type: 'POST',  
  4.                 data: person,  
  5.                 dataType: 'html',  
  6.                  contentType: 'application/json',  
  7.                  success: function (result) { alert(result); }  
  8.                 };  
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

把contentType改成json格式,那么得到的是出错的信息。

虽然person是json对象,但是jquery中的ajax,data会自动的被转换成查询字符串格式key1=value1&key2=value2这种形式,很显然这种形式不是json格式,因此会出错。

要避免转换成查询字符串格式,只需要设置processData为fasle即可。processData默认是true。

这里需要注意的是:当指定了contentType的时候,数据将不再按照Form Data的形式提交了,而是变成Request Data的形式提交。可以从图上的Request Header中看出。需要注意的是,Form Data提交的数据可以由FormCollection获得到。Request Data方式提交的则不能通过FormCollection获得。

如果把processData设置为默认值true。

再谈Jquery <a class=Ajax方法传递到action_MVC_04" height="381" src="https://img-blog.csdnimg.cn/img_convert/6c249e1761e50e0af6722cfa7b48875e.png" />

如果把processData设置为false。

再谈Jquery <a class=Ajax方法传递到action_MVC_05" height="286" src="https://img-blog.csdnimg.cn/img_convert/552a485d50dfe87f2dbbf900c04e3c36.png" />

以上两种方式,按照application/json的类型传给都会失败,因为json是基于文本的格式,上面两种方式传递的都不是json文本。因此会出错。


因此,把option改成:

 
  1. var option = {  
  2.     url: '/test/ReadPerson',  
  3.     type: 'POST',  
  4.     data:JSON.stringify(person),  
  5.     dataType: 'html',  
  6.     contentType: 'application/json',  
  7.     success: function (result) { alert(result); }  
  8. };  
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

则传递的就是json文本,因此根据命名匹配,就能获得值了。

再谈Jquery <a class=Ajax方法传递到action_MVC_06" height="440" src="https://img-blog.csdnimg.cn/img_convert/0e240b55afd9c6d0d8fefb6b3c139735.png" />


对于较为简单是数据类型,有时候不指定contentType也能通过命名匹配传值。但是对于稍微复杂点的数据类型,有时指定contentType: 'application/json',处理起来更加方便。

如果一个controller里的action方法是接受一个List类型的参数,比如:

public ActionResult ReadPersons(List<PersonModel> model)

那么js中先构造这样的一个json对象的数组。如下

 
  1. var persons = [{ 
  2.                 id: "001", 
  3.                 name: "zhangsan", 
  4.                 age: "20", 
  5.                 gender: true, 
  6.                 city: "shanghai" 
  7.             }, 
  8.             { 
  9.                 id: "002", 
  10.                 name: "lisi", 
  11.                 age: "21", 
  12.                 gender: false, 
  13.                 city: "beijing" 
  14.             } 
  15.             ]; 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

单纯一个数组传递是作为data传递是,Form Data也是无法识别出的。因此把这个数组再次组成一个json形式。如下:其中json的键值用model是为了能和controller中的参数名相同,可以匹配。 

 
  1. var jsonp = { model: persons }; 
  2.            var option = { 
  3.                url: '/test/ReadPersons', 
  4.                type: 'POST', 
  5.                data: jsonp, 
  6.                dataType: 'html', 
  7.                success: function (result) { alert(result); } 
  8.            }; 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

由于未指定contentType,因此是默认的application/x-www-form-urlencoded。此时是按照Form Data的方式传递的,

再谈Jquery <a class=Ajax方法传递到action_MVC_07" height="462" src="https://img-blog.csdnimg.cn/img_convert/25b895de274b5881156266ac3f799e91.png" />

可以从截图中看到。但是这种格式的数据,controller中只能获得指定model用2个元素,无法获得元素中属性的值。

再谈Jquery <a class=Ajax方法传递到action_MVC_08" height="200" src="https://img-blog.csdnimg.cn/img_convert/267a3c351d64d4c158b0bc9d806c7741.png" />

如果把data改成JSON.stringify(jsonp),如下:     

 
  1. var option = { 
  2.               url: '/test/ReadPersons', 
  3.               type: 'POST', 
  4.               data: JSON.stringify(jsonp), 
  5.               dataType: 'html', 
  6.               success: function (result) { alert(result); } 
  7.           };  
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

再谈Jquery <a class=Ajax方法传递到action_MVC_09" height="348" src="https://img-blog.csdnimg.cn/img_convert/843fa5ae1ac7cd862273f6f7722f20f7.png" />

那么传递过去的Form Data是一串字符串,controller跟无法识别出这个东西,因此获不到值。如果仅仅设置contentType: 'application/json',而传递的又不是json格式的数据,如下:

 
  1. var option = { 
  2.     url: '/test/ReadPersons', 
  3.     type: 'POST', 
  4.     data: jsonp, 
  5.     dataType: 'html', 
  6.     contentType: 'application/json', 
  7.     success: function (result) { alert(result); } 
  8. }; 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

因为jquery的ajax方法会把data转换成查询字符串,因此就变成如下的样子。这串文本当然不符合json格式,因此会出现下面的错误。

再谈Jquery <a class=Ajax方法传递到action_MVC_10" height="85" src="https://img-blog.csdnimg.cn/img_convert/4df3a327222255f607ea76eb7ca93205.png" />

再谈Jquery <a class=Ajax方法传递到action_MVC_11" height="175" src="https://img-blog.csdnimg.cn/img_convert/6d8ad6f286ba2c1873fb89ff0938e2e8.png" />

如果设置contentType: 'application/json',并且设置data: JSON.stringify(persons),如下:

 
  1. var option = { 
  2.                 url: '/test/ReadPersons', 
  3.                 type: 'POST', 
  4.                 data: JSON.stringify(persons), 
  5.                 dataType: 'html', 
  6.                 contentType: 'application/json', 
  7.                 success: function (result) { alert(result); } 
  8.             }; 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

那么可以获得到真正完整的json数据了

再谈Jquery <a class=Ajax方法传递到action_MVC_12" height="387" src="https://img-blog.csdnimg.cn/img_convert/6a6bc6b9283b7e5df5ecc7f34d984b7d.png" />


最后,此处再演示一个更复杂的参数类型,以便加深理解。

首先看一下Controller中的方法签名,TestClassB 和一个TestClassA的List。稍显复杂。 

 
  1. public ActionResult Fortest(TestClassB TB,List<TestClassA> TA) 
  2.         { 
  3.             string result = ""; 
  4.             return Content(result); 
  5.         } 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

再看TestClassA和TestClassB,更显复杂。但是结构要清晰的话,也不是很难。

 
  1. public class TestClassA 
  2.     { 
  3.        public string a1 { set; get; } 
  4.        public List<string> a2 { set; get; } 
  5.     } 
  6.     public class TestClassB 
  7.     { 
  8.         public string b1 { set; get; } 
  9.         public InnerTestClassC ITCC { set; get; } 
  10.         public class InnerTestClassC 
  11.         { 
  12.             public List<int> c1 { set; get; } 
  13.         } 
  14.     } 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

看js代码:逐步的构造出一个json格式。

 
  1. $("#btn").click(function () { 
  2.             var jsondata = { TB: {}, TA: [] }; 
  3.             jsondata.TB.b1 = "b1"; 
  4.             jsondata.TB.ITCC = {}; 
  5.             jsondata.TB.ITCC.c1 = new Array(1, 2, 3, 4); 
  6.             var ta1 = {}; 
  7.             ta1.a1 = "a1"; 
  8.             ta1.a2 = new Array("a", "b", "x", "y"); 
  9.            var ta2 = {}; 
  10.             ta2.a1 = "a2"; 
  11.             ta2.a2 = new Array("a2", "b2", "x2"); 
  12.             jsondata.TA.push(ta1); 
  13.             jsondata.TA.push(ta2); 
  14.             var option = { 
  15.                 url: '/test/Fortest', 
  16.                 type: 'POST', 
  17.                 data: JSON.stringify(jsondata), 
  18.                 dataType: 'html', 
  19.                 contentType: 'application/json', 
  20.                 success: function (result) { alert(result); } 
  21.             }; 
  22.             $.ajax(option); 
  23.         }); 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.

最终,发送出去的json字符串如下:

{"TB":{"b1":"b1","ITCC":{"c1":[1,2,3,4]}},"TA":[{"a1":"a1","a2":["a","b","x","y"]},{"a1":"a2","a2":["a2","b2","x2"]}]}

Controller接收到这个json串后,就能自动的匹配参数了。具体得到的参数如下截图:

再谈Jquery <a class=Ajax方法传递到action_MVC_13" height="276" src="https://img-blog.csdnimg.cn/img_convert/34ef6b2b57c518424db6f82a9756bad8.png" />

再谈Jquery <a class=Ajax方法传递到action_MVC_14" height="411" src="https://img-blog.csdnimg.cn/img_convert/19633961339aed4edba3ffcfdf8e3fca.png" />


总结:

1.不指定contentType的话,默认都是application/x-www-form-urlencoded方式发送。此时即便发送的是json格式的数据,默认情况下,jquery的ajax也会把他转为查询字符串的形式(可以通过修改ajax参数修改),以FormData的形式发送出去。

2.不指定contentType的时候,如果controller中的方法签名比较简单,那么即便是FormData形式的数据也能由MVC的命名匹配规则获取到数据。

3.指定contentType为'application/json'时候,发送的数据必须是符合json规范的字符串。通常,使用 JSON.stringify(jsondata)有较好的可读性,可以获得一个json字符串。当然,不是必须的。使用拼接的字符串,只要是符合json规范的,也是可以发送的。

4.如果contentType为'application/json'时,发送的data不是符合json规范的字符串,则会出错。

5.通常情况下,尽量指定contentType为'application/json',并且发送json字符串作为发送数据,这样可读性更好,并且对于复杂的函数签名,也能起到很好的匹配。


http://www.niftyadmin.cn/n/1869984.html

相关文章

$.ajax contenType是appliation/json的时候,spring mvc后台无法接受data参数

$.ajax contenType是appliation/json的时候&#xff0c;spring mvc后台无法接受data参数 做Redis监控工具的时候&#xff0c;发现$.ajax contenType是appliation/json的时候&#xff0c;在后台用spring mvc的Requestparam注解接收参数&#xff0c;始终接收不到。 前台代码&…

web编程基础——html

html 是什么&#xff1a;html标签 html 能做什么&#xff0c;怎么做&#xff1a; html 怎么运行&#xff1a;浏览器解析引擎和渲染引擎工作原理、http 协议 什么是 html html&#xff1a;hyper text markup language hyper&#xff1a;hyper high press er hi p er …

JS组件Bootstrap实现弹出框和提示框效果代码

前言&#xff1a;对于Web开发人员&#xff0c;弹出框和提示框的使用肯定不会陌生&#xff0c;比如常见的表格新增和编辑功能&#xff0c;一般常见的主要有两种处理方式&#xff1a;行内编辑和弹出框编辑。在增加用户体验方面&#xff0c;弹出框和提示框起着重要的作用&#xff…

web编程基础——javascript

javascript 是 netscape 公司的基于对象和事件驱动的编程语言 和 java 的不同之处&#xff1a; 1.所属公司不一样 java 是 sun 公司&#xff0c;现在是 oracle 公司&#xff0c;javascript 是 netscape 公司 2. js 是基于对象&#xff0c;java 是面向对象 3. js 是由浏览器…

js立即执行函数: (function ( ){})( ) 与 (function ( ){}( )) 有什么区别?

没有区别。 你需要明白 IIFE 的原理&#xff0c;我简单说一下&#xff1a; 复制代码代码如下: function foo() {...} // 这是定义&#xff0c;Declaration&#xff1b;定义只是让解释器知道其存在&#xff0c;但是不会运行。 foo(); // 这是语句&#x…

黑马高薪学习方法

原文地址&#xff1a;http://bbs.itheima.com/forum.php?modviewthread&tid63387&extrapage%3D1 此文章是黑马老学员给新学员的学习建议&#xff0c;一个来自高薪学员的心声&#xff0c;望仔细耐心看完&#xff0c;这将是你在黑马学习的重要指南。 四个半月的时光转瞬…

AJAX POST请求中参数以form data和request payload形式在servlet中的获取方式

HTTP请求中&#xff0c;如果是get请求&#xff0c;那么表单参数以namevalue&name1value1的形式附到url的后面&#xff0c;如果是post请求&#xff0c;那么表单参数是在请求体中&#xff0c;也是以namevalue&name1value1的形式在请求体中。通过chrome的开发者工具可以看…

JSP与SERVLET的关系

原文地址:http://blog.csdn.net/frank3g/article/details/4593426 综述&#xff1a;Java Servlet是JSP技术的基础&#xff0c;而且大型的Web应用程序的开发需要Java Servlet和JSP配合才能完成。现在许多Web服务器都支持Servlet&#xff0c;即使不直接支持Servlet的Web服务器&…