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 = 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;//状态:-2用户被锁定 -1用户名密码错误
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";//返回的结果 -2邮箱为空 -1邮箱格式不正确 0邮箱存在 1填写正确
if (string.isnullorempty(email))
{
result = "-2";//邮箱为空
}
else if (!isvalidemail(email))
{
result = "-1";//邮箱格式不正确
}
else if (userbll.sel_useremail(email) > 0)
{
result = "0";//邮箱存在
}
else
{
result = "1";//可以注册
}
return result;
}
[webmethod]
public string validateusername(string username)
{
string result = "0";//返回值:-1用户名长度为2-16;0用户名存在;1可以注册
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 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})(\]?)$");
}
}
webservice
webservice
<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>
ajax
以上就是jquery ajax调用webservice总结 的详细内容。
