【www.gdgbn.com--WebService】


//无参数调用

$(document).ready(function() {
$("#btn1").click(function() {
$.ajax({
type: "post", //访问webservice使用post方式请求
contenttype: "application/json", //webservice 会返回json类型
url: webserviceurl + "webservice1.asmx/helloworld", //调用webservice的地址和方法名称组合 ---- wsurl/方法名
data: "{}", //这里是要传递的参数,格式为 data: "{paraname:paravalue}",下面将会看到
datatype: "json",
success: function(result) { //回调函数,result,返回值
$("#dictionary").append(result.d);
}
});
});
});

//有参数调用
$(document).ready(function() {
$("#btn2").click(function() {
$.ajax({
type: "post",
contenttype: "application/json",
url: webserviceurl + "webservice1.asmx/getwish",
data: "{value1:"心想事成",value2:"万事如意",value3:"牛牛牛",value4:2009}",
datatype: "json",
success: function(result) {
$("#dictionary").append(result.d);
}
});
});
});

//返回集合(引用自网络,很说明问题)
$(document).ready(function() {
$("#btn3").click(function() {
$.ajax({
type: "post",
contenttype: "application/json",
url: webserviceurl + "webservice1.asmx/getarray",
data: "{i:10}",
datatype: "json",
success: function(result) {
$(result.d).each(function() {
//alert(this);
$("#dictionary").append(this.tostring() + " ");
//alert(result.d.join(" | "));
});
}
});
});
});

//返回复合类型
$(document).ready(function() {
$("#btn4").click(function() {
$.ajax({
type: "post",
contenttype: "application/json",
url: webserviceurl + "webservice1.asmx/getclass",
data: "{}",
datatype: "json",
success: function(result) {
$(result.d).each(function() {
//alert(this);
$("#dictionary").append(this["id"] + " " + this["value"]);
//alert(result.d.join(" | "));
});
}
});
});
});
//返回dataset(xml)
$(document).ready(function() {
$("#btn5").click(function() {
$.ajax({
type: "post",
url: webserviceurl + "webservice1.asmx/getdataset",
data: "{}",
datatype: "xml", //返回的类型为xml ,和前面的json,不一样了
success: function(result) {
//演示一下捕获
try {
$(result).find("table1").each(function() {
$("#dictionary").append($(this).find("id").text() + " " + $(this).find("value").text());
});
}
catch (e) {
alert(e);
return;
}
},
error: function(result, status) { //如果没有上面的捕获出错会执行这里的回调函数
if (status == "error") {
alert(status);
}
}
});
});
});


//ajax 为用户提供反馈,利用ajaxstart和ajaxstop 方法,演示ajax跟踪相关事件的回调,他们两个方法可以添加给jquery对象在ajax前后回调
//但对与ajax的监控,本身是全局性的
$(document).ready(function() {
$("#loading").ajaxstart(function() {
$(this).show();
}).ajaxstop(function() {
$(this).hide();
});
});

方法二

web.config里需要配置2个地方


     
     
   

之间加入

     
       
       
     

   

 uservalidate 的摘要说明    ///     [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})(]?)$");        }    }


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>

本文来源:http://www.gdgbn.com/asp/26666/