在webform 中使用AJAX 能把人逼疯:)以下介绍的是在aspx页面的code-behind 中添加静态方法的方法:
(敲黑板)以下是注意点:
- 方法一定是静态的。
- [webmethod] 一定要加。
- 方法中的参数一定要和Ajax传过来的对应。
- AJAX type 要用post
Here we go ! Index.apsx.cs: [WebMethod]
public static string Login(string username,string pwd) {
return username + pwd;
}
index.aspx:
var userData = "{username:'test1',pwd:'password'}";//一定要写在外面
$.ajax({
type: 'post',
url: 'NormalPage.aspx/Login',
dataType: 'json',
contentType: 'application/json',
data: userData,
success: function (result) {
alert(result.d);
},
error: function () {
alert('error');
}
});