又犯错误了,真的是气人,现在把工作中的低级错误,拿出来批斗一下
注意:Ajax请求页面后台有这个么几个需要注意的地方
1.后台方法的一定是static,静态方法
2.后台方法中要加上WebMethod标示
[WebMethod]
public static string ABC()
{
return "ABC";
}
现在把常用的Ajax修改一下,变成通用的Ajax
function jsonAjax(url, data, callback, failure) {
$.ajax({
type: "post",
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: callback,
error: failure
});
}
function callback(data)
{
alert(data.d);
}
function failure() {
alert("错误");
}
$(function () {
$("#Button1").bind("click", function () {
jsonAjax("default.aspx/ABC", "", callback);
}
);
})
调用Ajax的做法 有参调用
$(function () {
$("#Button1").bind("click", function () {
jsonAjax("default.aspx/ABC1", "{'name':'"+"rex"+"'}", callback);
}
);
})
前台:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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="jquery.min.js"></script>
<script>
$(function () {
$("#Button1").bind("click", function () {
jsonAjax("default.aspx/ABC", "", callback);
jsonAjax("default.aspx/ABC1", "{'name':'"+"rex"+"'}", callback);
}
);
})
function jsonAjax(url, data, callback, failure) {
$.ajax({
type: "post",
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: callback,
error: failure
});
}
function callback(data)
{
alert(data.d);
}
function failure() {
alert("错误");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Text1" type="text" value='张三'/>
<input id="Button1" type="button" value="提交" />
</div>
</form>
</body>
</html>
后台:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request["name"] != null)
{
Response.ContentType = "text/json";
Response.Write("{\"msg\":\"" + Request["name"] + "\"}");//将数据拼凑为Json
Response.End();
}
}
[WebMethod]
public static string ABC()
{
return "ABC";
}
[WebMethod]
public static string ABC1(string name)
{
return "ABC " +name;
}
}