关于 jquery+ajax向asp.net传递json的问题研究(呕心沥血、柳暗花明)

第一种方法:字典的方法

 //质检不合格
$('#Button3').click(function () {
if (!confirm('确定质检不合格吗?'))
return; var obj = new Object();
obj.x1 = 123;
obj.y1 = "abc";
//var jsonText = $.toJSON(obj);
var jsonText = JSON.stringify(obj);
//这个时候,jsonText 传递到asp.net后,asp.net 收到字典对象,而不是字符串的json对象
//jsonText = "'" + jsonText + "'";
alert(jsonText); $.ajax({
type: "POST",
url: "Default3.aspx/ss",
data: "{'str':" + jsonText + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
alert(msg.d);
},
error: function (x, e) {
alert("The call to the server side failed. " + x.responseText);
}
}); return false; }); //这里是结束
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json; public partial class Default3 : System.Web.UI.Page
{ public class qhftest
{ public int my_x1 { get; set; }
public string my_y1 { get; set; } public qhftest(int x1, string y1)
{
this.my_x1 = x1;
this.my_y1 = y1;
} } protected void Page_Load(object sender, EventArgs e)
{ }
[System.Web.Services.WebMethod]
public static string ss(object str)
{ //qhftest ee = JsonConvert.DeserializeObject<qhftest>(str.ToString()); //return ee.my_x1.ToString()+"---"+ee.my_y1.ToString(); /*
* 先转为Dictionary对象,再转为json字符串,再转为一个具体的对象
*/
Dictionary<string, object> tmp = (Dictionary<string, object>)str; qhftest ee = JsonConvert.DeserializeObject<qhftest>(JsonConvert.SerializeObject(tmp, Formatting.Indented)); string s = ""; foreach (string key in tmp.Keys)
{
s +="----" +String.Format("Key = {0}", key);
} return tmp.ToString(); }
}

第二种方法:呕心沥血的方法

  //质检不合格
$('#Button3').click(function () {
if (!confirm('确定质检不合格吗?'))
return; var obj = new Object();
obj.x1 = ;
obj.y1 = "abc";
//var jsonText = $.toJSON(obj);
var jsonText = JSON.stringify(obj);
jsonText = "'" + jsonText + "'";
/*
* 加了两边的单引号后,就变成字符串了,asp.net就非常容易转换
*/ $.ajax({
type: "POST",
url: "Default3.aspx/ss",
data: "{'str':" + jsonText + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
alert(msg.d);
},
error: function (x, e) {
alert("The call to the server side failed. " + x.responseText);
}
}); return false; }); //这里是结束
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json; public partial class Default3 : System.Web.UI.Page
{ public class qhftest
{ public int my_x1 { get; set; }
public string my_y1 { get; set; } public qhftest(int x1, string y1)
{
this.my_x1 = x1;
this.my_y1 = y1;
} } protected void Page_Load(object sender, EventArgs e)
{ }
[System.Web.Services.WebMethod]
public static string ss(object str)
{ qhftest ee = JsonConvert.DeserializeObject<qhftest>(str.ToString()); return ee.my_x1.ToString()+"---"+ee.my_y1.ToString(); }
}
上一篇:服务器部署minio


下一篇:TCP的定时器系列 — 保活定时器