DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> jQuery入門知識 >> JQuery特效代碼 >> 再談Jquery Ajax方法傳遞到action(補充)
再談Jquery Ajax方法傳遞到action(補充)
編輯:JQuery特效代碼     

之前寫過一篇文章Jquery Ajax方法傳值到action,本文是對該文的補充
假設 controller中的方法是如下:

. 代碼如下:
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定義如下:

. 代碼如下:
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<PersonModel> 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格式的數據,如下:

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

因為jquery的ajax方法會把data轉換成查詢字符串,因此就變成如下的樣子。這串文本當然不符合json格式,因此會出現下面的錯誤。

clipboard[3]

clipboard[4]


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

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

那麼可以獲得到真正完整的json數據了

clipboard[5]


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

. 代碼如下:
public ActionResult Fortest(TestClassB TB,List<TestClassA> TA)
        {
            string result = "";
            return Content(result);
        }

再看TestClassA和TestClassB,更顯復雜。但是結構要清晰的話,也不是很難。

. 代碼如下:
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代碼:逐步的構造出一個json格式。

. 代碼如下:
$("#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);
        });

最終,發送出去的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串後,就能自動的匹配參數了。具體得到的參數如下截圖:

clipboard[6]

clipboard[7]

總結:

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字符串作為發送數據,這樣可讀性更好,並且對於復雜的函數簽名,也能起到很好的匹配。

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

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved