JSON

ajax、json一些整理(2)

字号+ 作者:H5之家 来源:H5之家 2017-07-15 17:01 我要评论( )

ajax、json一些整理(2),script type=text/javascript$(document).ready(function(){$(#btn).click(function(){$.ajax({type:

正文

<script type="text/javascript"> $(document).ready(function(){ $("#btn").click(function(){ $.ajax({ type: 'POST', url: "/Home/MyAjax", data: { val1: $("#txt1").val(), val2: $("#txt2").val(), val3: $("#txt3").val(), val4: $("#txt4").val(), }, dataType: "json" }); }); }); </script> <input type="button" value="click" /> <input type="text" value="" /> <input type="text" value="" /> <input type="text" value="" /> <input type="text" value="" />

  data是json数据。传递到的Action是/Home/MyAjax。那么在Action方法处接收的方式如下:

public ActionResult MyAjax(string val1) { string val2 = Request["val2"].ToString(); string val3 = Request.Form["val3"].ToString(); string val4 = Request.Params["val4"].ToString(); return Content("ViewUserControl1"); }

  或者接收参数为FormCollection,也有同样的效果。

public ActionResult MyAjax(FormCollection f) { string val2 = f["val2"].ToString(); string val3 = f["val3"].ToString(); string val4 = f["val4"].ToString(); return Content("ViewUserControl1"); }

  MVC3的强悍之处,是它是基于变量参数命名匹配的机制,就是说它尽可能的查找能够有相同变量名字的值。对于上面的例子,我们甚至可以构造出一个class,如下:

public class aclass { public string val1 { set; get; } public string val2 { set; get; } public string val3 { set; get; } public string val4 { set; get; } }

  那么就可以设置参数类型为aclass

public ActionResult MyAjax(aclass f) { return Content(f.val1+f.val2+f.val3+f.val4); }

  注意,aclass类的属性名就是json的key的名字,只要符合一致,它就能匹配,不得不说强悍。

  补充:

假设 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"
引自#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文本。因此会出错。

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • 用Python将excel文件导出成json

    用Python将excel文件导出成json

    2017-07-16 12:00

  • JSON解析器--实现代码

    JSON解析器--实现代码

    2017-07-15 16:00

  • JSON学习---合并Merge,克隆Clone,指向子对象ForcePath

    JSON学习---合并Merge,克隆Clone,指向子对象ForcePath

    2017-07-15 15:01

  • JSON学习笔记(四)

    JSON学习笔记(四)

    2017-07-15 15:00

网友点评