前端
HtmlPage1.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form>
<input type="text" id="txt1" /><br />
<input type="text" id="txt2" /><br />
<input type="button" id="btn1" value="验证" οnclick="btn1_onclick()" />
</form>
</body>
</html>
<script src="jquery.min.js"></script>
<script>
function btn1_onclick() {
var txt1 = $("#txt1").val();
var txt2 = document.getElementById("txt2").value;
$.ajax({
url: "Handler1.ashx",
type: "post",
data: JSON.stringify({ txt1: txt1, txt2: txt2 }),
dataType: "json",
success: function (msg) {
if (msg[0] == "yes") {
alert(msg[1]);
}
else {
alert(msg[1]);
}
},
});
}
</script>后端Handler1.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.IO;
namespace WebTest
{
/// <summary>
/// Handler1 的摘要说明
/// </summary>
//定义一个类用来将前端传递过来的数据进行反序列化
public class MSG
{
public string txt1 { set; get; }
public string txt2 { set; get; }
}
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//定义两组数据,待会儿序列化之后传递给前端
List<string> ls1 = new List<string>() {"yes","正确"};
List<string> ls2 = new List<string>() { "no","错误"};
//接收前端传递过来的数据
context.Response.ContentType = "application/json";
var data = context.Request;
var stream = new StreamReader(data.InputStream).ReadToEnd();
var msgdata = new JavaScriptSerializer().Deserialize<MSG>(stream);
//验证前端的数据,并传递相应的数据给前端
if (msgdata.txt1 == "lzj" && msgdata.txt2 == "999")
{
context.Response.Write(new JavaScriptSerializer().Serialize(ls1));
}
else
{
context.Response.Write(new JavaScriptSerializer().Serialize(ls2));
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}结果
版权声明:本文为sinat_32832727原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。