Jquery ajax调用webservice总结
jquery ajax调用webservice(C#)要注意的几个事项:
1、web.config里需要配置2个地方
<httpHandlers>
<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"/>
</httpHandlers>
在<system.web></system.web>之间加入
<webServices>
<protocols>
<add name="HttpPost" />
<add name="HttpGet" />
</protocols>
</webServices>
2.正确地编写webserivce的代码
/// <summary>
/// UserValidate 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[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 = ;
int gpoint = ;
try
{
DataTable dt = UserBll.ExecuteUserAllInfo(username); if (dt.Rows.Count > )
{
ipoint = int.Parse(dt.Rows[]["iPoint"].ToString());
gpoint = int.Parse(dt.Rows[]["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, -);
int ipoint = ;
int gpoint = ;
DataTable dt = UserBll.ExecuteUserAllInfo(userName); if (dt.Rows.Count > )
{
ipoint = int.Parse(dt.Rows[]["iPoint"].ToString());
gpoint = int.Parse(dt.Rows[]["gPoint"].ToString());
}
returnVal = "{'user':{'id':'" + info.UserId.ToString() + "','name':'" + info.UserName + "','message':'" + rp.getUserMsg(userName) + "','ipoint':'" + ipoint.ToString() + "','gpoint':'" + gpoint.ToString() + "'}}";
}
else
{
int ids = ;//状态:-2用户被锁定 -1用户名密码错误
switch (state)
{
case EnumLoginState.Err_Locked:
ids = -;
break;
case EnumLoginState.Err_UserNameOrPwdError:
ids = -;
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(-);
cookie.Domain = DFHon.Config.BaseConfig.getV("weblogin");
HttpContext.Current.Response.AppendCookie(cookie);
}
return "";
}
DFHon.Content.user UserBll = new DFHon.Content.user();
[WebMethod]
public string ValidateUserEmail(string email)
{
string result = "";//返回的结果 -2邮箱为空 -1邮箱格式不正确 0邮箱存在 1填写正确
if (string.IsNullOrEmpty(email))
{
result = "-2";//邮箱为空
}
else if (!IsValidEmail(email))
{
result = "-1";//邮箱格式不正确
}
else if (UserBll.sel_useremail(email) > )
{
result = "";//邮箱存在
}
else
{
result = "";//可以注册
}
return result;
} [WebMethod]
public string ValidateUserName(string username)
{
string result = "";//返回值:-1用户名长度为2-16;0用户名存在;1可以注册
if (username == "" || username == null || username.Length < || username.Length > )
{
result = "-1";
}
else if (UserBll.sel_username(username) != )
{
result = "";
}
else
{
result = "";
}
return result;
} public bool IsValidEmail(string strIn)
{ // Return true if strIn is 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、前台JQuery代码
<script>
$(function() {
$("#userloging").show();
//登录框处理开始
//加载登录状态
$.ajax({
type: "POST", //访问WebService使用Post方式请求
contentType: "application/json;charset=utf-8", //WebService 会返回Json类型
url: "/API/Service/UserValidate.asmx/ValidateUserLogState", //调用WebService
data: "{}", //Email参数
dataType: 'json',
beforeSend: function(x) { x.setRequestHeader("Content-Type", "application/json; charset=utf-8"); },
error: function(x, e) { },
success: function(response) { //回调函数,result,返回值
$("#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();
}
}
});
//登录
$("#userlogbutton").click(function() { var username = $("#username").val();
var userpwd = $("#userpassword").val();
if (username != "" && userpwd != "") {
$("#userloging").show();
$.ajax({
type: "POST", //访问WebService使用Post方式请求
contentType: "application/json;charset=utf-8", //WebService 会返回Json类型
url: "/API/Service/UserValidate.asmx/UserLogin", //调用WebService
data: "{userName:'" + username + "',userPwd:'" + userpwd + "'}", //Email参数
dataType: 'json',
beforeSend: function(x) { x.setRequestHeader("Content-Type", "application/json; charset=utf-8"); },
error: function(x, e) {
},
success: function(result) { //回调函数,result,返回值
$("#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("用户被锁定!请30分钟后再登录!");
$("#username").focus();
break;
case -1:
alert("用户名或密码错误!请核对您的用户名和密码!");
$("#userpassword").focus();
break;
default:
alert("登录失败!请核对您的用户名和密码之后重试!");
$("#userpassword").focus();
break;
}
}
}
});
}
else if (username == "") {
alert("用户名不能为空!");
$("#username").focus();
}
else if (userpwd == "") {
alert("密码不能为空!");
$("#userpassword").focus();
}
});
//退出
$("#logout").click(function() {
$("#userloging").show();
$.ajax({
type: "POST", //访问WebService使用Post方式请求
contentType: "application/json;utf-8", //WebService 会返回Json类型
url: "/API/Service/UserValidate.asmx/UserLogout", //调用WebService
data: "{}", //Email参数
dataType: 'json',
beforeSend: function(x) { x.setRequestHeader("Content-Type", "application/json; charset=utf-8"); },
success: function(result) { //回调函数,result,返回值
$("#userloging").hide();
if (result.d > 0) {
$("#userloginsucced").hide();
$("#userloginbox").show();
}
}
}); }); //登录框处理结束 });
</script>
Jquery ajax调用webservice总结的更多相关文章
- Jquery Ajax 调用 WebService
原文:http://www.cnblogs.com/andiki/archive/2010/05/17/1737254.html jquery ajax调用webservice(C#)要注意的几个事项 ...
- Jquery AJAX 调用WebService服务
对Jquery+JSON+WebService的一点认识 文章不错:http://www.cnblogs.com/tyb1222/archive/2011/10/13/2210549.html Jqu ...
- Ajax调用WebService接口样例
在做手机端h5的应用时,通过Ajax调用http接口时没啥问题的:但有些老的接口是用WebService实现的,也来不及改成http的方式,这时通过Ajax调用会有些麻烦,在此记录具体实现过程.本文使 ...
- Ajax调用WebService
前台代码: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1 ...
- Ajax调用WebService(一)
Ajax调用WebService(一) http://www.cnblogs.com/leslies2/archive/2011/01/26/1934889.html 分类: Ajax 使用技术 We ...
- jquery ajax调用返回json格式数据处理
Ajax请求默认的都是异步的 如果想同步 async设置为false就可以(默认是true) var html = $.ajax({ url: "some.php", async: ...
- WCF入门教程(四)通过Host代码方式来承载服务 一个WCF使用TCP协议进行通协的例子 jquery ajax调用WCF,采用System.ServiceModel.WebHttpBinding System.ServiceModel.WSHttpBinding协议 学习WCF笔记之二 无废话WCF入门教程一[什么是WCF]
WCF入门教程(四)通过Host代码方式来承载服务 Posted on 2014-05-15 13:03 停留的风 阅读(7681) 评论(0) 编辑 收藏 WCF入门教程(四)通过Host代码方式来 ...
- ASP.NET实现二维码 ASP.Net上传文件 SQL基础语法 C# 动态创建数据库三(MySQL) Net Core 实现谷歌翻译ApI 免费版 C#发布和调试WebService ajax调用WebService实现数据库操作 C# 实体类转json数据过滤掉字段为null的字段
ASP.NET实现二维码 using System;using System.Collections.Generic;using System.Drawing;using System.Linq;us ...
- Jquery Ajax调用asmx出错问题
1.//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释. [System.Web.Script.Services.ScriptService] 这个 ...
随机推荐
- Windows Server 2008修改IE浏览器级别便于使用
1.降低IE安全级别 Win 2008默认IE的安全级别为“高”,并且不能随意调整,在浏览网页的时候有些会有一些限制,可以打开注册表编辑器进行设置,定位到 [HKEY_LOCAL_MACHINE\S ...
- State Threads——异步回调的线性实现
State Threads——异步回调的线性实现 原文链接:http://coolshell.cn/articles/12012.html 本文的标题看起来有点拗口,其实State Threads库就 ...
- JavaScript正则表达式方法总结
str.match(reg) 1.reg没有全局标志g,match将只执行一次匹配.匹配成功返回一个数组,arr = [$0,$1,$2,...,index,str],匹配失败返回null. arr中 ...
- SQLServer中获取特定表的所有列名
1.获取特定表的所有列名: Select Name FROM SysColumns Where id=Object_Id('tableName') 参考:http://blog.csdn.net/wu ...
- clearfix--清除浮动
.clearfix { zoom: ; display: table; width: %; } .clearfix:after { content: " "; display: b ...
- kafka环境搭建及librdkafka测试
kafka环境搭建及librdkafka测试 (2016-04-05 10:18:25) 一.kafka环境搭建(转自http://kafka.apache.org/documentation.h ...
- 【11-23】window常用知识
tips msconfig :管理应用程序加载启动项,也可以通过我的计算机查看 service.msc :管理windows本地服务 命令行:net start :显示所有启动的服务,不加分号 net ...
- html中的 button,input-button, image, input-image的区别
hmtl中 为了验证 form的 action提交属性, 是指 表单提交到的 页面, 可以是任意 性质的页面, 如:html页面, php页面, asp页面等都可以, 实际在测试的时候, 可以就写 提 ...
- UvaLive6661 Equal Sum Sets dfs或dp
UvaLive6661 PDF题目 题意:让你用1~n中k个不同的数组成s,求有多少种组法. 题解: DFS或者DP或打表. 1.DFS 由于数据范围很小,直接dfs每种组法统计个数即可. //#pr ...
- hdu4888 Redraw Beautiful Drawings 最大流+判环
hdu4888 Redraw Beautiful Drawings Time Limit: 3000/1500 MS (Java/Others) Memory Limit: 65536/6553 ...