65.9K
CodeProject 正在变化。 阅读更多。
Home

使用简单的 JavaScript 调用 WCF 服务

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (5投票s)

2010年12月23日

CPOL
viewsIcon

31778

WCF 服务

大家好,虽然有很多方法(例如 Jquery 等)可以通过 Ajax 请求访问 WCF 服务或任何服务,但我实现了一种简洁明了的方式来以 JSON 格式调用 WCF 服务。
// base URL for the Ajax call to service
var baseUrl = "https://:54976/RestServiceImpl.svc/";
//Ajax request function for making Ajax calling through other object
function AjaxRequest(baseurl, type, callbackResponse, parameterString) {
    this.BaseURL = baseurl;
    this.Type = type;
    this.Callback = callbackResponse;
    this.createXmlRequestObject();
    this.ParemeterString = parameterString;
}
// Create XMLHTTP OBJECT
AjaxRequest.prototype.createXmlRequestObject = function() {
    if (window.ActiveXObject) { // INTERNET EXPLORER
        try {
            this.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
            this.xmlHttp = false;
        }
    }
    else { // OTHER BROWSERS
        try {
            this.xmlHttp = new XMLHttpRequest()
        } catch (f) {
            this.xmlHttp = false;
        }
    }
    if (!this.xmlHttp) { // RETURN THE OBJECT OR DISPLAY ERROR
        alert('there was an error creating the xmlhttp object');
    } else {
        //return this.xmlhttp;
    }
}
AjaxRequest.prototype.MakeRequest = function() {
    try {
        // PROCEED ONLY IF OBJECT IS NOT BUSY
        if (this.xmlHttp.readyState === 4 || this.xmlHttp.readyState === 0) {
            // EXECUTE THE PAGE ON THE SERVER AND PASS QUERYSTRING
            this.xmlHttp.open(this.Type, this.BaseURL, false);
            var that = this;
            // DEFINE METHOD TO HANDLE THE RESPONSE
            this.xmlHttp.onreadystatechange = function() {
                try {
                    // MOVE FORWARD IF TRANSACTION COMPLETE
                    alert(that.xmlHttp.readyState);
                    if (that.xmlHttp.readyState == 4) {
                        alert(that.xmlHttp.status);
                        // STATUS OF 200 INDICATES COMPLETED CORRECTLY
                        if (that.xmlHttp.status == 200) {
                            // WILL HOLD THE XML DOCUMENT
                            var xmldoc;
                            if (window.ActiveXObject) { // INTERNET EXPLORER
                                xmldoc = new ActiveXObject("Microsoft.XMLDOM");
                                xmldoc.async = "false";
                                that.Callback(that.xmlHttp.responseText);
                            }
                            else { // OTHER BROWSERS
                                //writeMessage("MakeRequest", that.xmlHttp.responseText);
                                that.Callback(that.xmlHttp.responseText);
                            }
                        }
                    }
                }
                catch (e)
                { alert(e) }
            }
            switch (this.Type) {
                case "GET":
                    //this.xmlHttp.setRequestHeader("Content-type", "application/json");
                    // MAKE CALL
                    this.xmlHttp.send(this.BaseURL);
                    break;
                case "POST":
                    this.xmlHttp.setRequestHeader("Content-type", "application/json");
                    this.xmlHttp.send(this.ParemeterString)
            }
        }
        else {
            // IF CONNECTION IS BUSY, WAIT AND RETRY
            setTimeout('GetAllAppsService', 5000);
        }
    } catch (e) {
        alert(e);
    }
}
这里 ajaxrequest 是我们将其视为一个类的函数。 让我概述一下 ajaxrequest 的参数:BaseURL:基本 URL 是服务 URL。 Type:哪种类型的请求“GET”或“POST”。 Callbackresponse:回调响应用作从对象调用的回调函数,并且将在发送请求后保存服务器的响应。 Parameterstring:参数字符串是请求的主体。 注意:如果请求是 JSON 格式,则 ParameterString 应该是 JSON 字符串(在 POST 请求的情况下)。 现在我将解释如何调用它。
AuthenticateLogin.prototype.SendDetailsToServer = function(parameters, localId) {
    var url = baseUrl + "SignUpUser";
    var parameterString = "{";
    for (var i = 0; i < parameters.length; i++) {
        parameterString = parameterString + '"'
                  + parameters[i][0] + '":"'
                  + parameters[i][1] + '" ,';
    }
    parameterString = parameterString.slice(0, parameterString.length - 1);
    //writeMessage("AddNewReminderToServer", "Local id : "+localId);
    parameterString = parameterString + "}";
    var ajaxRequestObject = new AjaxRequest(url, "POST", function(responseText) {
        var jsonobj = eval('(' + responseText + ')');
        var result = jsonobj.SignUpUserResult;
        if (result == "Successful") {
            alert("SuccessfullyMail sent and you will redirect to login Page");
            window.location = "https://:54976/UI/latestLogin.htm";
        }
        else {
            alert("Message sending Fail! Please try again");
            window.location.reload(true);
        }
        //        writeMessage("handleresponse", jsonstr);
        //        writeMessage(" -> local id :", ajaxRequestObject.TempItemID);
    }, parameterString);
    //writeMessage("AddNewReminderToServer", "Local id in ajax object : " + ajaxRequestObject.TempItemID);
    ajaxRequestObject.MakeRequest();
}
就这样。 希望你喜欢。
© . All rights reserved.