JQuery扩展提交JSON数据
1 $.fn.extend({ 2 // $(that).children() 只读取 id 以 "json_" 开始的元素, 3 // 且 id 的命名规则一定是 json_[id]_[dataType] 4 // [id] 是不能包含 _ 的任何有意义的名称 5 // [dataType] 是该元素的数据类型,根据 c# 的基本数据类型命名,用途待续... 6 toSubmitJSON: function (url) { 7 8 var that = this; 9 var elementIdPattern = /^json_[a-zA-Z0-9]+_[a-z]+$/; //!important 10 11 var jsonEntity = function (elementId, elementValue) { 12 var splitFrom = elementId.split("_"); 13 this.id = splitFrom[1]; 14 this.dataType = splitFrom[2]; 15 this.value = elementValue; 16 this.toJSONString = function () { 17 return '{"id":"' + this.id + '","dataType":"' + this.dataType + '","value":"' + this.value + '"}'; 18 }; 19 }; 20 21 var getJSONData = function () { 22 var jsonBuilder = ""; 23 var child = $(that).children(); 24 child.each(function (index) { 25 26 var element = child.eq(index); 27 var elementId = element.attr("id"); 28 29 if (elementId != undefined) { 30 if (elementIdPattern.test(elementId)) { 31 var entity = new jsonEntity(elementId, element.val()); 32 if (jsonBuilder == "") { 33 jsonBuilder = entity.toJSONString(); 34 } 35 else { 36 jsonBuilder = jsonBuilder + "," + entity.toJSONString(); 37 } 38 } 39 } 40 }); 41 if (jsonBuilder != "") { 42 jsonBuilder = "[" + jsonBuilder + "]"; 43 } 44 return jsonBuilder; 45 } 46 47 //jsondata为空,说明读取不到任何按规定格式命名的元素. 48 var jsondata = getJSONData(); 49 if (jsondata == "") { 50 alert("missing json data element."); 51 } 52 else { 53 $.ajax({ 54 url: url, 55 type: "POST", 56 dataType: "json", 57 contentType: "application/json", 58 data: jsondata, 59 cache: false, 60 error: function (jqXHR) { 61 alert(jqXHR.statusText); 62 }, 63 success: function (data) { 64 alert(data); 65 }, 66 complete: function () { 67 alert("complete"); 68 } 69 }); 70 } 71 } 72 });
结合 Newtonsoft.json 获取数据
public ActionResult JsonData(){ string json = new System.IO.StreamReader(this.HttpContext.Request.InputStream).ReadToEnd(); var result=Newtonsoft.Json.JsonConvert.DeserializeObject(json); return Json(result.ToString()); }
@{ ViewBag.Title = "Index"; } <h2>Index</h2> <script type="text/javascript" src="Scripts/jquery.submitJSON.js"></script> <div id="jsondiv1"> <input id="json_myUsername_string" type="text" value="admin" /> <input id="json_myPassword_string" type="text" value="123456" /> <input type="button" id="jsondata" value="submit" onclick="$($('#jsondiv1').toSubmitJSON('../DataExe/JsonData'))" /> </div>