//页面
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ajaxtest.aspx.cs" Inherits="ajaxtest.ajaxtest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="Scripts/jquery-1.8.2.js"></script>
<script src="Scripts/jquery-1.8.2.min.js"></script>
<script>
//html
function JudgeUserName() {
$.ajax({
url: "getajax.ashx?id=1",
type: "GET",
dataType: "html",
data: "userName=" + $("#txtName").val(),
beforeSend: function (XMLHttpRequest) {
$("#showResult").text("正在查询...");
// Pause(this,100000);
},
success: function (msg) {
$("#showResult").html(msg);
$("#showResult").css("color", "red");
},
complete: function (XMLHttpRequest, textStatus) {
//隐藏正在查询图片
},
error: function () {
//错误处理
}
});
}
//json
function getjsonname() {
$.ajax({
url: "getajax.ashx",
type: "Post",
dataType: "json",
data: getjson(),
beforeSend: function (XMLHttpRequest) {
$("#showResult").text("正在查询...");
},
success: function (msg) {
$("#showResult").html(msg.Name + msg.Age);
$("#showResult").css("color", "red");
},
complete: function (XMLHttpRequest, textStatus) {
//隐藏正在查询图片
},
error: function () {
//错误处理
}
});
}
function getjson()
{
var jsondata = { "name": "jack", "age": 24 };
return jsondata;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="txtName" />
<input type="button" value="gethtml" οnclick="JudgeUserName()" />
<input type="button" value="postjson" οnclick="getjsonname()" />
<a οnclick=""></a>
<div id="showResult"></div>
</div>
</form>
</body>
</html>
//ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.Script.Serialization;
namespace ajaxtest
{
/// <summary>
/// getajax 的摘要说明
/// </summary>
public class getajax : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
// context.Response.Write("Hello World");
//html
if (context.Request["id"] != null)
{
context.Response.Write("get传值" + context.Request["id"].ToString());
if (context.Request["userName"] != null)
{
context.Response.Write("您输入的数据为" + context.Request["userName"].ToString());
}
}
//json
if (context.Request.Params["name"] != null && context.Request.Params["age"] != null)
{
string jsonString = "{\"Age\":" + context.Request.Params["age"] + ",\"Name\":\"" + context.Request.Params["name"].ToString() + "\"}";
context.Response.Write(jsonString);
}
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}