Turn from: http://www.cnblogs.com/andiki/archive/2010/05/17/1737254.html
Several things to note in jquery Ajax call WebService (C #):
1, web.config need to configure 2 places
<remove verb= "*" path= "*.asmx"/>
<add verb= "*" path= "*.asmx" validate= "false" Type= "System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, version=1.0.61025.0, culture=neutral, publickeytoken=31bf3856ad364e35 "/>
Join in between <system.web></system.web>
<webServices>
<protocols>
<add name= "HttpPost"/>
<add name= "HttpGet"/>
</protocols>
</webServices>
2. Correctly write Webserivce code
<summary>
Summary description of Uservalidate
</summary>
[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = wsiprofiles.basicprofile1_1)]
[System.ComponentModel.ToolboxItem (False)]
To allow the use of ASP.net AJAX to invoke this Web service from a script, uncomment the downlink.
[System.Web.Script.Services.ScriptService]
public class UserValidate:System.Web.Services.WebService
{
DFHon.Content.Common.rootPublic rp = new DFHon.Content.Common.rootPublic ();
[WebMethod]
[Scriptmethod (Responseformat = Responseformat.json)]
public string Validateuserlogstate ()
{
string result = "";
HttpCookie cookie = httpcontext.current.request.cookies["Dhfonmenberinfo"];
if (cookie!= null)
{
String username = System.Web.HttpUtility.UrlDecode (cookie["Menbername"]);
int ipoint = 0;
int gpoint = 0;
Try
{
DataTable dt = Userbll.executeuserallinfo (username);
if (dt. Rows.Count > 0)
{
ipoint = Int. Parse (dt. rows[0] ["iPoint"]. ToString ());
gpoint = Int. Parse (dt. rows[0] ["gpoint"]. ToString ());
}
}
Catch
{ }
result = "{' user ': {' id ': '" + cookie["UserId"] + "', ' name ': '" + username + "', ' message ': '" + rp.getusermsg (Dfhon. Global.CurrentCookie.UserName) + "', ' ipoint ': '" + ipoint. ToString () + "', ' gpoint ': '" + gpoint. ToString () + "'}}";
}
Else
{
result = ' {' user ': {' id ': ' 0 ', ' name ': ', ' message ': ' 0 ', ' ipoint ': ' 0 ', ' gpoint ': ' 0 '}} ';
}
return result;
}
[WebMethod]
[Scriptmethod (Responseformat = Responseformat.json)]
public string Userlogin (string userName, String userpwd)
{
String returnval = "";
Try
{
Globaluserinfo info;
DFHon.Content.UserLogin _userlogin = new DFHon.Content.UserLogin ();
Enumloginstate state = _userlogin.personlogin (Httputility.urldecode (userName), userpwd, out info);
if (state = = Enumloginstate.succeed)
{
DFHon.Global.CurrentCookie.Set (info);
DFHon.API.PDO.DiscuzNT.PassportLogin.UserLogin (Server.urldecode (userName), Userpwd,-1);
int ipoint = 0;
int gpoint = 0;
DataTable dt = Userbll.executeuserallinfo (userName);
if (dt. Rows.Count > 0)
{
ipoint = Int. Parse (dt. rows[0] ["iPoint"]. ToString ());
gpoint = Int. Parse (dt. rows[0] ["gpoint"]. ToString ());
}
ReturnVal = "{' user ': {' id ': '" + info. Userid.tostring () + "', ' name ': '" + info. UserName + "', ' message ': '" + rp.getusermsg (UserName) + "', ' ipoint ': '" + ipoint. ToString () + "', ' gpoint ': '" + gpoint. ToString () + "'}}";
}
Else
{
int ids = 0; Status:-2 user Locked-1 username password error
Switch (state)
{
Case enumloginstate.err_locked:
ids =-2;
break;
Case ENUMLOGINSTATE.ERR_USERNAMEORPWDERROR:
ids =-1;
break;
Default:
break;
}
ReturnVal = "{' user ': {' id ': ' + ids +" ', ' name ': ', ' message ': ' 0 ', ' ipoint ': ' 0 ', ' gpoint ': ' 0 '}} ";
}
}
Catch
{
ReturnVal = ' {' user ': {' id ': ' 0 ', ' name ': ', ' message ': ' 0 ', ' ipoint ': ' 0 ', ' gpoint ': ' 0 '}} ';
}
return returnval;
}
[WebMethod]
public string Userlogout ()
{
if (httpcontext.current.request.cookies["Dhfonmenberinfo"]!= null)
{
HttpCookie cookie = new HttpCookie ("Dhfonmenberinfo");
Cookie. Expires = System.DateTime.Now.AddDays (-1);
Cookie. Domain = DFHon.Config.BaseConfig.getV ("Weblogin");
HttpContext.Current.Response.AppendCookie (cookie);
}
return "1";
}
DFHon.Content.user USERBLL = new DFHon.Content.user ();
[WebMethod]
public string Validateuseremail (string email)
{
string result = "0"; Returned results-2 mailbox is empty-1 mailbox format is incorrect 0 mailbox exists 1 fill in correctly
if (string. IsNullOrEmpty (email))
{
result = "-2"; Mailbox is empty
}
else if (! IsValidEmail (email))
{
result = "-1"; Mailbox format is not correct
}
else if (userbll.sel_useremail (email) > 0)
{
result = "0"; Mailbox exists
}
Else
{
result = "1"; Can register
}
return result;
}
[WebMethod]
public string Validateusername (string username)
{
string result = "0"; return value:-1 username is 2-16;0 username exists; 1 can be registered
if (username = = "" | | Username = = NULL | | Username. Length < 2 | | Username. Length > 16)
{
result = "-1";
}
else if (Userbll.sel_username (username)!= 0)
{
result = "0";
}
Else
{
result = "1";
}
return result;
}
public bool IsValidEmail (string strin)
{//return TRUE if Strin are in valid e-mail format.
Return System.Text.RegularExpressions.Regex.IsMatch (Strin, @ "^" ^ [\w-\.] +) @ (\[[0-9]{1,3}\. [0-9] {1,3}\. [0-9] {1,3}\.) | (([\w-]+\.) +)) ([a-za-z]{2,4}| [0-9] {1,3}) (\]?) $ " );
}
3, front desk jquery code
< script >
$ (function () {
$ ("#userloging"). Show ();
Login Box Processing Start
Load Login Status
$.ajax ({
Type: "POST",//Access WebService use POST method request
ContentType: "Application/json;charset=utf-8",//WebService will return JSON type
URL: "/api/service/uservalidate.asmx/validateuserlogstate",//Call WebService
Data: "{}",//email parameter
DataType: ' JSON ',
Beforesend:function (x) {X.setrequestheader ("Content-type", "Application/json; Charset=utf-8 ");},
Error:function (x, E) {},
Success:function (response) {//callback function, result, return value
$ ("#userloging"). Hide ();
var json = eval (' + RESPONSE.D + ') ');
var userid = json.user.id;
if (UserID > 0) {
$ ("#spanusername"). HTML (json.user.name);
$ ("#spanmessagenum"). HTML (json.user.message);
$ ("#userloginsucced"). Show ();
$ ("#userloginbox"). Hide ();
}
}
});
Login
$ ("#userlogbutton"). Click (function () {
var username = $ ("#username"). Val ();
var userpwd = $ ("#userpassword"). Val ();
if (username!= "" && userpwd!= "") {
$ ("#userloging"). Show ();
$.ajax ({
Type: "POST",//Access WebService use POST method request
ContentType: "Application/json;charset=utf-8",//WebService will return JSON type
URL: "/api/service/uservalidate.asmx/userlogin",//Call WebService
Data: "{userName: '" + userName + "', Userpwd: '" + Userpwd + "'}",//email parameter
DataType: ' JSON ',
Beforesend:function (x) {X.setrequestheader ("Content-type", "Application/json; Charset=utf-8 ");},
Error:function (x, E) {
},
Success:function (Result) {//callback function, result, return value
$ ("#userloging"). Hide ();
var json = eval (' + result.d + ') ');
var userid = json.user.id;
if (UserID > 0) {
$ ("#spanusername"). HTML (json.user.name);
$ ("#spanmessagenum"). HTML (json.user.message);
$ ("#userloginsucced"). Show ();
$ ("#userloginbox"). Hide ();
}
else {
Switch (userid) {
Case-2:
Alert ("User is locked.) Please login again in 30 minutes. " );
$ ("#username"). focus ();
break;
Case-1:
Alert ("User name or password is incorrect.) Please check your username and password. " );
$ ("#userpassword"). focus ();
break;
Default:
Alert ("Logon failed.") Please check your username and password and try again. " );
$ ("#userpassword"). focus ();
break;
}
}
}
});
}
else if (username = "") {
Alert ("User name cannot be empty.) " );
$ ("#username"). focus ();
}
else if (userpwd = "") {
Alert (password cannot be empty.) " );
$ ("#userpassword"). focus ();
}
});
Exit
$ ("#logout"). Click (function () {
$ ("#userloging"). Show ();
$.ajax ({
Type: "POST",//Access WebService use POST method request
ContentType: "Application/json;utf-8",//WebService will return JSON type
URL: "/api/service/uservalidate.asmx/userlogout",//Call WebService
Data: "{}",//email parameter
DataType: ' JSON ',
Beforesend:function (x) {X.setrequestheader ("Content-type", "Application/json; Charset=utf-8 ");},
Success:function (Result) {//callback function, result, return value
$ ("#userloging"). Hide ();
if (Result.d > 0) {
$ ("#userloginsucced"). Hide ();
$ ("#userloginbox"). Show ();
}
}
});
}); End of Login box processing
});
</script>