首页 > web前端 > js教程 > 正文

再谈Jquery Ajax方法传递到action(补充)_jquery

php中文网
发布: 2016-05-16 16:48:46
原创
1088人浏览过

之前写过一篇文章Jquery Ajax方法传值到action,本文是对该文的补充
假设 controller中的方法是如下:

讯飞智作-讯飞配音
讯飞智作-讯飞配音

讯飞智作是一款集AI配音、虚拟人视频生成、PPT生成视频、虚拟人定制等多功能的AI音视频生产平台。已广泛应用于媒体、教育、短视频等领域。

讯飞智作-讯飞配音 67
查看详情 讯飞智作-讯飞配音
复制代码 代码如下:

public ActionResult ReadPerson(PersonModel model) 
        { 
            string s = model.ToString(); 
            return Content(s); 
        }

public ActionResult ReadPersons(List model) 
        { 
            string result = ""; 
            if (model == null) return Content(result); 
            foreach (var s in model) 
            { 
                result += s.ToString(); 
                result += "-------------"; 
            }
            return Content(result); 
        }

其中PersonModel定义如下:

复制代码 代码如下:

public class PersonModel 
    { 
        public int id 
        { 
            set; 
            get; 
        } 
        public string name 
        { 
            set; 
            get; 
        }

        public int age 
        { 
            set; 
            get; 
        }

        public bool gender 
        { 
            set; 
            get; 
        } 
        public string city 
        { 
            set; 
            get; 
        }

        public override string ToString() 
        { 
            string s = string.Format(@"id:{0} 
name:{1} 
age:{2} 
gender:{3} 
city:{4} 
", id, name, age, gender, city); 
            return s; 
        } 
    }

那么controller方法分别接受单个model和一个model的List。采用通过ajax传递参数。
对于传递单个参数的情况,假设js代码如下:

复制代码 代码如下:

var person = { 
               id: "001", 
               name: "zhangsan", 
               age: "20", 
               gender: true, 
               city: "shanghai" 
           };

var option = { 
               url: '/test/ReadPerson', 
               type: 'POST', 
               data: person, 
               dataType: 'html', 
               success: function (result) { alert(result); } 
           }; 
$.ajax(option);

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

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

将option 的代码改成如下

复制代码 代码如下:

var option = { 
               url: '/test/ReadPerson', 
               type: 'POST', 
               data: JSON.stringify(person), 
               dataType: 'html', 
               success: function (result) { alert(result); } 
           }; 
$.ajax(option);

其中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

看请求头的截图:

clipboard[4]_thumb

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

将将option 的代码改成如下

复制代码 代码如下:

var option = { 
                url: '/test/ReadPerson', 
                type: 'POST', 
                data: person, 
                dataType: 'html', 
                 contentType: 'application/json', 
                 success: function (result) { alert(result); } 
                }; 

把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。

image_thumb[3]

如果把processData设置为false。

image_thumb[2]

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

因此,把option改成:

复制代码 代码如下:

var option = { 
    url: '/test/ReadPerson', 
    type: 'POST', 
    data:JSON.stringify(person), 
    dataType: 'html', 
    contentType: 'application/json', 
    success: function (result) { alert(result); } 
}; 

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

clipboard[8]_thumb

对于较为简单是数据类型,有时候不指定contentType也能通过命名匹配传值。但是对于稍微复杂点的数据类型,有时指定contentType: 'application/json',处理起来更加方便。
如果一个controller里的action方法是接受一个List类型的参数,比如:
public ActionResult ReadPersons(List model)
那么js中先构造这样的一个json对象的数组。如下

复制代码 代码如下:

var persons = [{
                id: "001",
                name: "zhangsan",
                age: "20",
                gender: true,
                city: "shanghai"
            },
            {
                id: "002",
                name: "lisi",
                age: "21",
                gender: false,
                city: "beijing"
            }
            ];

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

复制代码 代码如下:

var jsonp = { model: persons };
           var option = {
               url: '/test/ReadPersons',
               type: 'POST',
               data: jsonp,
               dataType: 'html',
               success: function (result) { alert(result); }
           };

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

clipboard

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

clipboard[1]

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

复制代码 代码如下:

var option = {
              url: '/test/ReadPersons',
              type: 'POST',
              data: JSON.stringify(jsonp),
              dataType: 'html',
              success: function (result) { alert(result); }
          };

clipboard[2]

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

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

复制代码 代码如下:

public ActionResult ReadPerson(PersonModel model) 
        { 
            string s = model.ToString(); 
            return Content(s); 
        }

public ActionResult ReadPersons(List model) 
        { 
            string result = ""; 
            if (model == null) return Content(result); 
            foreach (var s in model) 
            { 
                result += s.ToString(); 
                result += "-------------"; 
            }
            return Content(result); 
        }

其中PersonModel定义如下:

复制代码 代码如下:

public class PersonModel 
    { 
        public int id 
        { 
            set; 
            get; 
        } 
        public string name 
        { 
            set; 
            get; 
        }

        public int age 
        { 
            set; 
            get; 
        }

        public bool gender 
        { 
            set; 
            get; 
        } 
        public string city 
        { 
            set; 
            get; 
        }

        public override string ToString() 
        { 
            string s = string.Format(@"id:{0} 
name:{1} 
age:{2} 
gender:{3} 
city:{4} 
", id, name, age, gender, city); 
            return s; 
        } 
    }

那么controller方法分别接受单个model和一个model的List。采用通过ajax传递参数。
对于传递单个参数的情况,假设js代码如下:

复制代码 代码如下:

var person = { 
               id: "001", 
               name: "zhangsan", 
               age: "20", 
               gender: true, 
               city: "shanghai" 
           };

var option = { 
               url: '/test/ReadPerson', 
               type: 'POST', 
               data: person, 
               dataType: 'html', 
               success: function (result) { alert(result); } 
           }; 
$.ajax(option);

从chrome中截图可以看到如下:
clipboard[3]0

复制代码 代码如下:


public ActionResult ReadPerson(PersonModel model) 
        { 
            string s = model.ToString(); 
            return Content(s); 
        }

public ActionResult ReadPersons(List model) 
        { 
            string result = ""; 
            if (model == null) return Content(result); 
            foreach (var s in model) 
            { 
                result += s.ToString(); 
                result += "-------------"; 
            }
            return Content(result); 
        }

其中PersonModel定义如下:

复制代码 代码如下:

public class PersonModel 
    { 
        public int id 
        { 
            set; 
            get; 
        } 
        public string name 
        { 
            set; 
            get; 
        }

        public int age 
        { 
            set; 
            get; 
        }

        public bool gender 
        { 
            set; 
            get; 
        } 
        public string city 
        { 
            set; 
            get; 
        }

        public override string ToString() 
        { 
            string s = string.Format(@"id:{0} 
name:{1} 
age:{2} 
gender:{3} 
city:{4} 
", id, name, age, gender, city); 
            return s; 
        } 
    }

那么controller方法分别接受单个model和一个model的List。采用通过ajax传递参数。
对于传递单个参数的情况,假设js代码如下:

复制代码 代码如下:

var person = { 
               id: "001", 
               name: "zhangsan", 
               age: "20", 
               gender: true, 
               city: "shanghai" 
           };

var option = { 
               url: '/test/ReadPerson', 
               type: 'POST', 
               data: person, 
               dataType: 'html', 
               success: function (result) { alert(result); } 
           }; 
$.ajax(option);

从chrome中截图可以看到如下:
clipboard[4]1


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

复制代码 代码如下:

public ActionResult ReadPerson(PersonModel model) 
        { 
            string s = model.ToString(); 
            return Content(s); 
        }

public ActionResult ReadPersons(List model) 
        { 
            string result = ""; 
            if (model == null) return Content(result); 
            foreach (var s in model) 
            { 
                result += s.ToString(); 
                result += "-------------"; 
            }
            return Content(result); 
        }

其中PersonModel定义如下:

复制代码 代码如下:

public class PersonModel 
    { 
        public int id 
        { 
            set; 
            get; 
        } 
        public string name 
        { 
            set; 
            get; 
        }

        public int age 
        { 
            set; 
            get; 
        }

        public bool gender 
        { 
            set; 
            get; 
        } 
        public string city 
        { 
            set; 
            get; 
        }

        public override string ToString() 
        { 
            string s = string.Format(@"id:{0} 
name:{1} 
age:{2} 
gender:{3} 
city:{4} 
", id, name, age, gender, city); 
            return s; 
        } 
    }

那么controller方法分别接受单个model和一个model的List。采用通过ajax传递参数。
对于传递单个参数的情况,假设js代码如下:

复制代码 代码如下:

var person = { 
               id: "001", 
               name: "zhangsan", 
               age: "20", 
               gender: true, 
               city: "shanghai" 
           };

var option = { 
               url: '/test/ReadPerson', 
               type: 'POST', 
               data: person, 
               dataType: 'html', 
               success: function (result) { alert(result); } 
           }; 
$.ajax(option);

从chrome中截图可以看到如下:
clipboard[5]2


最后,此处再演示一个更复杂的参数类型,以便加深理解。
首先看一下Controller中的方法签名,TestClassB 和一个TestClassA的List。稍显复杂。

复制代码 代码如下:

public ActionResult ReadPerson(PersonModel model) 
        { 
            string s = model.ToString(); 
            return Content(s); 
        }

public ActionResult ReadPersons(List model) 
        { 
            string result = ""; 
            if (model == null) return Content(result); 
            foreach (var s in model) 
            { 
                result += s.ToString(); 
                result += "-------------"; 
            }
            return Content(result); 
        }

其中PersonModel定义如下:

复制代码 代码如下:

public class PersonModel 
    { 
        public int id 
        { 
            set; 
            get; 
        } 
        public string name 
        { 
            set; 
            get; 
        }

        public int age 
        { 
            set; 
            get; 
        }

        public bool gender 
        { 
            set; 
            get; 
        } 
        public string city 
        { 
            set; 
            get; 
        }

        public override string ToString() 
        { 
            string s = string.Format(@"id:{0} 
name:{1} 
age:{2} 
gender:{3} 
city:{4} 
", id, name, age, gender, city); 
            return s; 
        } 
    }

那么controller方法分别接受单个model和一个model的List。采用通过ajax传递参数。
对于传递单个参数的情况,假设js代码如下:

复制代码 代码如下:

var person = { 
               id: "001", 
               name: "zhangsan", 
               age: "20", 
               gender: true, 
               city: "shanghai" 
           };

var option = { 
               url: '/test/ReadPerson', 
               type: 'POST', 
               data: person, 
               dataType: 'html', 
               success: function (result) { alert(result); } 
           }; 
$.ajax(option);

从chrome中截图可以看到如下:
clipboard[6]3

复制代码 代码如下:


public ActionResult ReadPerson(PersonModel model) 
        { 
            string s = model.ToString(); 
            return Content(s); 
        }

public ActionResult ReadPersons(List model) 
        { 
            string result = ""; 
            if (model == null) return Content(result); 
            foreach (var s in model) 
            { 
                result += s.ToString(); 
                result += "-------------"; 
            }
            return Content(result); 
        }

其中PersonModel定义如下:

复制代码 代码如下:

public class PersonModel 
    { 
        public int id 
        { 
            set; 
            get; 
        } 
        public string name 
        { 
            set; 
            get; 
        }

        public int age 
        { 
            set; 
            get; 
        }

        public bool gender 
        { 
            set; 
            get; 
        } 
        public string city 
        { 
            set; 
            get; 
        }

        public override string ToString() 
        { 
            string s = string.Format(@"id:{0} 
name:{1} 
age:{2} 
gender:{3} 
city:{4} 
", id, name, age, gender, city); 
            return s; 
        } 
    }

那么controller方法分别接受单个model和一个model的List。采用通过ajax传递参数。
对于传递单个参数的情况,假设js代码如下:

复制代码 代码如下:

var person = { 
               id: "001", 
               name: "zhangsan", 
               age: "20", 
               gender: true, 
               city: "shanghai" 
           };

var option = { 
               url: '/test/ReadPerson', 
               type: 'POST', 
               data: person, 
               dataType: 'html', 
               success: function (result) { alert(result); } 
           }; 
$.ajax(option);

从chrome中截图可以看到如下:
clipboard[7]4

总结:

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字符串作为发送数据,这样可读性更好,并且对于复杂的函数签名,也能起到很好的匹配。

本文出自 “一只博客” 博客

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号