JS:
var list = {
name: "张三",
sex:"男"
}
//记得引用jquery,否则会报错!
$.post("ajax/test.ashx", list, function (result) {
console.log(result)
if (result.success) {
alert(result.txt)
} else {
alert(result.msg)
}
});
ashx:
<%@ WebHandler Language="C#" Class="test" %>
using System;
using System.Web;
public class test : IHttpHandler {
public void ProcessRequest (HttpContext context) {
bool success = false;
string msg = "";
string txt = "";
try
{
success = true;
txt = "操作成功!传过来的姓名为:" + context.Request["name"] + ",性别为:" + context.Request["sex"];
}
catch (Exception ex)
{
success = false;
msg = "操作失败!错误信息为:" + ex.Message.ToString();
}
var resultObj = new
{
success = success,
msg = msg,
txt = txt
};
context.Response.ContentType = "application/json;charset;utf-8";
context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(resultObj));
}
public bool IsReusable {
get {
return false;
}
}
}
前端返回结果:
我这里直接在控制台写Ajax,显示成功返回。