亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

再談Jquery Ajax方法傳遞到action(補(bǔ)充)

 更新時(shí)間:2014年05月12日 00:13:24   作者:  
之前寫過(guò)一篇文章Jquery Ajax方法傳值到action,本文是對(duì)該文的補(bǔ)充

之前寫過(guò)一篇文章Jquery Ajax方法傳值到action,本文是對(duì)該文的補(bǔ)充
假設(shè) controller中的方法是如下:

復(fù)制代碼 代碼如下:

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

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

其中PersonModel定義如下:

復(fù)制代碼 代碼如下:

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方法分別接受單個(gè)model和一個(gè)model的List。采用通過(guò)ajax傳遞參數(shù)。
對(duì)于傳遞單個(gè)參數(shù)的情況,假設(shè)js代碼如下:

復(fù)制代碼 代碼如下:

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

傳遞的數(shù)據(jù)是一串Form數(shù)據(jù),根據(jù)命名匹配的原則,也是可以取得數(shù)據(jù)的。
image_thumb

將option 的代碼改成如下

復(fù)制代碼 代碼如下:

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 ] ] ),根據(jù)ECMA-262標(biāo)準(zhǔn)stringify 函數(shù)返回的是JSON格式的字符串。它可以有3個(gè)參數(shù)。摘抄如下:
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.
默認(rèn)的ContentType的屬性值是"application/x-www-form-urlencoded"
引自http://www.w3.org/TR/html401/interact/forms.html#adef-enctype

看請(qǐng)求頭的截圖:

clipboard[4]_thumb

因此,傳遞到controller的是一個(gè)json字符串,MVC根據(jù)命名匹配也是可以獲得到參數(shù)的值。

將將option 的代碼改成如下

復(fù)制代碼 代碼如下:

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

把contentType改成json格式,那么得到的是出錯(cuò)的信息。
雖然person是json對(duì)象,但是jquery中的ajax,data會(huì)自動(dòng)的被轉(zhuǎn)換成查詢字符串格式key1=value1&key2=value2這種形式,很顯然這種形式不是json格式,因此會(huì)出錯(cuò)。
要避免轉(zhuǎn)換成查詢字符串格式,只需要設(shè)置processData為fasle即可。processData默認(rèn)是true。
這里需要注意的是:當(dāng)指定了contentType的時(shí)候,數(shù)據(jù)將不再按照Form Data的形式提交了,而是變成Request Data的形式提交??梢詮膱D上的Request Header中看出。需要注意的是,F(xiàn)orm Data提交的數(shù)據(jù)可以由FormCollection獲得到。Request Data方式提交的則不能通過(guò)FormCollection獲得。
如果把processData設(shè)置為默認(rèn)值true。

image_thumb[3]

如果把processData設(shè)置為false。

image_thumb[2]

以上兩種方式,按照application/json的類型傳給都會(huì)失敗,因?yàn)閖son是基于文本的格式,上面兩種方式傳遞的都不是json文本。因此會(huì)出錯(cuò)。

因此,把option改成:

復(fù)制代碼 代碼如下:

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

則傳遞的就是json文本,因此根據(jù)命名匹配,就能獲得值了。

clipboard[8]_thumb

對(duì)于較為簡(jiǎn)單是數(shù)據(jù)類型,有時(shí)候不指定contentType也能通過(guò)命名匹配傳值。但是對(duì)于稍微復(fù)雜點(diǎn)的數(shù)據(jù)類型,有時(shí)指定contentType: 'application/json',處理起來(lái)更加方便。
如果一個(gè)controller里的action方法是接受一個(gè)List類型的參數(shù),比如:
public ActionResult ReadPersons(List<PersonModel> model)
那么js中先構(gòu)造這樣的一個(gè)json對(duì)象的數(shù)組。如下

復(fù)制代碼 代碼如下:

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

單純一個(gè)數(shù)組傳遞是作為data傳遞是,F(xiàn)orm Data也是無(wú)法識(shí)別出的。因此把這個(gè)數(shù)組再次組成一個(gè)json形式。如下:其中json的鍵值用model是為了能和controller中的參數(shù)名相同,可以匹配。

復(fù)制代碼 代碼如下:

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

由于未指定contentType,因此是默認(rèn)的application/x-www-form-urlencoded。此時(shí)是按照Form Data的方式傳遞的,

clipboard

可以從截圖中看到。但是這種格式的數(shù)據(jù),controller中只能獲得指定model用2個(gè)元素,無(wú)法獲得元素中屬性的值。

clipboard[1]

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

復(fù)制代碼 代碼如下:

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

clipboard[2]

那么傳遞過(guò)去的Form Data是一串字符串,controller跟無(wú)法識(shí)別出這個(gè)東西,因此獲不到值。如果僅僅設(shè)置contentType: 'application/json',而傳遞的又不是json格式的數(shù)據(jù),如下:

那么傳遞過(guò)去的Form Data是一串字符串,controller跟無(wú)法識(shí)別出這個(gè)東西,因此獲不到值。如果僅僅設(shè)置contentType: 'application/json',而傳遞的又不是json格式的數(shù)據(jù),如下:

復(fù)制代碼 代碼如下:

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

因?yàn)閖query的ajax方法會(huì)把data轉(zhuǎn)換成查詢字符串,因此就變成如下的樣子。這串文本當(dāng)然不符合json格式,因此會(huì)出現(xiàn)下面的錯(cuò)誤。

clipboard[3]

clipboard[4]


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

復(fù)制代碼 代碼如下:

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

那么可以獲得到真正完整的json數(shù)據(jù)了

clipboard[5]


最后,此處再演示一個(gè)更復(fù)雜的參數(shù)類型,以便加深理解。
首先看一下Controller中的方法簽名,TestClassB 和一個(gè)TestClassA的List。稍顯復(fù)雜。

復(fù)制代碼 代碼如下:

public ActionResult Fortest(TestClassB TB,List<TestClassA> TA)
        {
            string result = "";
            return Content(result);
        }

再看TestClassA和TestClassB,更顯復(fù)雜。但是結(jié)構(gòu)要清晰的話,也不是很難。

復(fù)制代碼 代碼如下:

public class TestClassA
    {
       public string a1 { set; get; }
       public List<string> a2 { set; get; }
    }
    public class TestClassB
    {
        public string b1 { set; get; }
        public InnerTestClassC ITCC { set; get; }
        public class InnerTestClassC
        {
            public List<int> c1 { set; get; }
        }
    }

看js代碼:逐步的構(gòu)造出一個(gè)json格式。

復(fù)制代碼 代碼如下:

$("#btn").click(function () {
            var jsondata = { TB: {}, TA: [] };
            jsondata.TB.b1 = "b1";
            jsondata.TB.ITCC = {};
            jsondata.TB.ITCC.c1 = new Array(1, 2, 3, 4);
            var ta1 = {};
            ta1.a1 = "a1";
            ta1.a2 = new Array("a", "b", "x", "y");
           var ta2 = {};
            ta2.a1 = "a2";
            ta2.a2 = new Array("a2", "b2", "x2");
            jsondata.TA.push(ta1);
            jsondata.TA.push(ta2);
            var option = {
                url: '/test/Fortest',
                type: 'POST',
                data: JSON.stringify(jsondata),
                dataType: 'html',
                contentType: 'application/json',
                success: function (result) { alert(result); }
            };
            $.ajax(option);
        });

最終,發(fā)送出去的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接收到這個(gè)json串后,就能自動(dòng)的匹配參數(shù)了。具體得到的參數(shù)如下截圖:

clipboard[6]

clipboard[7]

總結(jié):

1.不指定contentType的話,默認(rèn)都是application/x-www-form-urlencoded方式發(fā)送。此時(shí)即便發(fā)送的是json格式的數(shù)據(jù),默認(rèn)情況下,jquery的ajax也會(huì)把他轉(zhuǎn)為查詢字符串的形式(可以通過(guò)修改ajax參數(shù)修改),以FormData的形式發(fā)送出去。
2.不指定contentType的時(shí)候,如果controller中的方法簽名比較簡(jiǎn)單,那么即便是FormData形式的數(shù)據(jù)也能由MVC的命名匹配規(guī)則獲取到數(shù)據(jù)。
3.指定contentType為'application/json'時(shí)候,發(fā)送的數(shù)據(jù)必須是符合json規(guī)范的字符串。通常,使用 JSON.stringify(jsondata)有較好的可讀性,可以獲得一個(gè)json字符串。當(dāng)然,不是必須的。使用拼接的字符串,只要是符合json規(guī)范的,也是可以發(fā)送的。
4.如果contentType為'application/json'時(shí),發(fā)送的data不是符合json規(guī)范的字符串,則會(huì)出錯(cuò)。
5.通常情況下,盡量指定contentType為'application/json',并且發(fā)送json字符串作為發(fā)送數(shù)據(jù),這樣可讀性更好,并且對(duì)于復(fù)雜的函數(shù)簽名,也能起到很好的匹配。

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

相關(guān)文章

最新評(píng)論