前台Ajax代码:
1 var obj;
2 function GetObject() {
3 $.ajax({
4 type: "POST",
5 url: "Test.aspx/GetObject",
6 contentType: "application/json; charset=utf-8",
7 data: "{'name':'" + $("#TB_Name").val() + "'}",
8 dataType: 'json',
9 success: function(data) {
10 obj = jQuery.parseJSON(data.d);
11 if (obj == null) { alert("未能查找到此單號對應的資料"); }
12 },
13 error: function(jqXHR, textStatus, errorThrown) {
14 alert(textStatus + " " + errorThrown);
15 }
16 });
17 }
2 function GetObject() {
3 $.ajax({
4 type: "POST",
5 url: "Test.aspx/GetObject",
6 contentType: "application/json; charset=utf-8",
7 data: "{'name':'" + $("#TB_Name").val() + "'}",
8 dataType: 'json',
9 success: function(data) {
10 obj = jQuery.parseJSON(data.d);
11 if (obj == null) { alert("未能查找到此單號對應的資料"); }
12 },
13 error: function(jqXHR, textStatus, errorThrown) {
14 alert(textStatus + " " + errorThrown);
15 }
16 });
17 }
後台Test.aspx的GetObject方法:
using System;
using System.Collections.Generic;
using System.Web.Services;
using Newtonsoft.Json;
public partial class Form_Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetObject(string name)
{
//通过参数获取对象
TestObject obj = new TestObject(name);
return JsonConvert.SerializeObject(obj);
}
}
using System.Collections.Generic;
using System.Web.Services;
using Newtonsoft.Json;
public partial class Form_Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetObject(string name)
{
//通过参数获取对象
TestObject obj = new TestObject(name);
return JsonConvert.SerializeObject(obj);
}
}
前台通过Ajax提交对象到後台:
function SaveToOrder() {
obj.Name = $("#TB_Name").val();
$.ajax({
type: "POST",
url: "Test.aspx/SaveObject",
contentType: "application/json; charset=utf-8",
data: "{'objString':'" + JSON.stringify(obj) + "'}",
dataType: 'json',
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
});
}
obj.Name = $("#TB_Name").val();
$.ajax({
type: "POST",
url: "Test.aspx/SaveObject",
contentType: "application/json; charset=utf-8",
data: "{'objString':'" + JSON.stringify(obj) + "'}",
dataType: 'json',
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
});
}
台後接收提交的信息,并处理:
[WebMethod]
public static bool SaveObject(string objString)
{
try
{
TestObject obj = JsonConvert.DeserializeObject<TestObject >(objString);
public static bool SaveObject(string objString)
{
try
{
TestObject obj = JsonConvert.DeserializeObject<TestObject >(objString);
//处理信息
}
catch (Exception ex) { return false }
return true;
}
}
catch (Exception ex) { return false }
return true;
}
文章来源:http://www.cnblogs.com/badtree/articles/2242515.html