小編給大家分享一下ASP.NET如何用Ajax返回Json對象,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
一、新建一個html頁面,如注冊頁面"Register.htm"
<!DOCTYPE html>
<html >
<head>
<title>用戶注冊</title>
<meta charset="utf-8" />
<style type="text/css">
.msg
{
color:Red;
}
</style>
</head>
<body>
<!--
因為是ajax提交,html表單控件可以不必放在form里,且不能使用提交按紐(type="submit"),而使用普通按紐(type="button")
-->
用戶名:<input type="text" name="id" id="id" /><span id="idMsg" class="msg"></span><br /> <!-- span用來顯示錯誤信息 -->
密 碼:<input type="password" name="pwd" id="pwd" /><span id="pwdMsg" class="msg"></span><br />
姓 名:<input type="text" name="name" id="xm" /><span id="nameMsg" class="msg"></span><br />
<input id="btnReg" type="button" value="注冊" />
<script type="text/javascript" src="bootstrap/js/jquery.js">
</script>
<script src="reg.js" type="text/javascript"></script>
</body>
</html>二、新建一js文件,如:reg.js
$(function() {
//定義清除錯誤信息的函數
function clearMsg() {
$(".msg").html("");
}
//定義獲取表單數據的函數,注意返回json對象
function formData() {
return {
id: $("#id").val(),
pwd: $("#pwd").val(),
name: $("#xm").val()
};
}
//定義注冊功能的函數
function reg() {
var url = "Register.ashx";
var data = formData();
clearMsg();
$.ajax({
type: 'GET', //自動會把json對象轉換為查詢字符串附在url后面如:http://localhost:49521/Register.ashx?id=a&pwd=b&name=c
url: url,
dataType: 'json', //要求服務器返回一個json類型的數據,如:{"success":true,"message":"注冊成功"}
contentType: 'application/json',//發送信息給服務器時,內容編碼的類型
data: data, //提交給服務器的數據,直接使用json對象的數據,如:{"id":"a","pwd":"b","name":"c"}?。ㄈ绻骿son格式的字符串,可使用用JSON.stringify(data))
success: function(responseData) {//如果響應成功(即200)
if (responseData.success == true) {//responseData也是json格式,如:{"success":true,"message":"注冊成功"}
alert(responseData.message);
} else {
var msgs = responseData.msgs;//msgs對象是一個數組,如下所示:
//{"success":false,"message":"注冊失敗","msgs":[{"id":"pwdMsg","message":"密碼不能為空."},{"id":"nameMsg","message":"姓名不能為空."}]}
for (var i = 0; i < msgs.length; i++) {
$('#' + msgs[i].id).html(msgs[i].message);
}
}
},
error: function() {
//要求為Function類型的參數,請求失敗時被調用的函數。該函數有3個參數,即XMLHttpRequest對象、錯誤信息、捕獲的錯誤對象(可選)。ajax事件函數如下:
//function(XMLHttpRequest, textStatus, errorThrown){
//通常情況下textStatus和errorThrown只有其中一個包含信息
//this; //調用本次ajax請求時傳遞的options參數
alert(arguments[1]);
}
});//ajax
}
//定義一個初始化函數
function init() {
$("#btnReg").click(function() {
reg();
});
}
//調用初始化函數
init();
});三、處理ajax請求
方法一:手動拼接json字符串
新建一般處理程序,如:Register.ashx
using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;
namespace WebLogin
{
/// <summary>
/// $codebehindclassname$ 的摘要說明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Register1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";//設置響應內容的格式是json格式
string id = context.Request["id"];
string pwd = context.Request["pwd"];
string name = context.Request["name"];
List<string> msgList = new List<string>();
if (String.IsNullOrEmpty(id))
{
msgList.Add("{\"id\":\"idMsg\",\"message\":\"用戶名不能為空.\"}");
}
if (pwd==null || pwd=="")
{
msgList.Add("{\"id\":\"pwdMsg\",\"message\":\"密碼不能為空.\"}");//形如:{"id":"pwdMsg","message":"密碼不能為空."}
}
if (name==null || name=="")
{
msgList.Add("{\"id\":\"nameMsg\",\"message\":\"姓名不能為空.\"}");
}
string responseText = "";
if (msgList.Count == 0)
{
//調用后臺代碼寫入數據庫
responseText = "{\"success\":true,\"message\":\"注冊成功\"}";
}
else
{
string msgsValue = "";
for (int i = 0; i < msgList.Count; i++)
{
msgsValue += msgList[i] + ",";//將列表中的每一個字符串連接起來,用","隔開,不過最后還會多","
}
msgsValue=msgsValue.Substring(0, msgsValue.Length - 1);//去掉末尾的","
msgsValue = "[" + msgsValue + "]";//用"[]"括起來,如:[{"id":"pwdMsg","message":"密碼不能為空."},{"id":"nameMsg","message":"姓名不能為空."}]
responseText = "{\"success\":false,\"message\":\"注冊失敗\",\"msgs\":" + msgsValue + "}";
//最的形如:{"success":false,"message":"注冊失敗","msgs":[{"id":"pwdMsg","message":"密碼不能為空."},{"id":"nameMsg","message":"姓名不能為空."}]}
}
context.Response.Write(responseText);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}方法二:使用Json.NET工具來將C#對象轉換json輸出
1、新建信息類“Msg.cs”
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace WebLogin
{
public class Msg
{
private string id;
public string Id
{
get { return id; }
set { id = value; }
}
private string message;
public string Message
{
get { return message; }
set { message = value; }
}
public Msg(string id, string message)
{
this.id = id;
this.message = message;
}
}
}2、新建返回json對象的類“ResponseData.cs”
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
namespace WebLogin
{
public class ResponseData
{
private bool success;
public bool Success
{
get { return success; }
set { success = value; }
}
private string message;
public string Message
{
get { return message; }
set { message = value; }
}
private List<Msg> msgs;
public List<Msg> Msgs
{
get { return msgs; }
set { msgs = value; }
}
public ResponseData(bool success, string message)
{
this.success = success;
this.message = message;
}
public ResponseData(bool success, string message, List<Msg> msgs)
{
this.success = success;
this.message = message;
this.msgs = msgs;
}
}
}3、去官網下載Json.NET,并復制引用
官網:http://www.newtonsoft.com/json
下載地址:http://pan.baidu.com/s/1nvz9JBV
下載解壓后將“Newtonsoft.Json.dll”復制到項目的“bin”目錄中,并引用(注意和.net版本保持一致)
4、新建一般處理程序“reg.ashx”
using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;//引入
namespace WebLogin
{
/// <summary>
/// $codebehindclassname$ 的摘要說明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class reg : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";//設置響應內容的格式是json格式
string id = context.Request["id"];
string pwd = context.Request["pwd"];
string name = context.Request["name"];
List<Msg> msgs = new List<Msg>();
if (String.IsNullOrEmpty(id))
{
msgs.Add(new Msg("idMsg", "用戶名不能為空."));
}
if (String.IsNullOrEmpty(pwd))
{
msgs.Add(new Msg("pwdMsg", "密碼不能為空."));
}
if (String.IsNullOrEmpty(name))
{
msgs.Add(new Msg("nameMsg", "姓名不能為空."));
}
ResponseData rData;
if (msgs.Count == 0)
{
//調用注冊方法,寫入數據庫
rData = new ResponseData(true, "注冊成功.");
}
else
{
rData = new ResponseData(false, "注冊失敗.", msgs);
}
context.Response.Write(JsonConvert.SerializeObject(rData));//直接調用方法將rData轉換為json字符串
}
public bool IsReusable
{
get
{
return false;
}
}
}
}四、完成效果如圖

以上是“ASP.NET如何用Ajax返回Json對象”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。