简体   繁体   English

如何从JavaScript使用WCF Web服务

[英]How to use wcf webservice from javaScript

We would like to use the same WCF web service to be used from JavaScript. 我们希望使用与JavaScript相同的WCF Web服务。 How is this done. 怎么做 We want to access database from JavaScript through WCF web service. 我们希望通过WCF Web服务从JavaScript访问数据库。 In two different domains 在两个不同的领域

This is a simple JavaScript ping function I use to connect to a WCF service - basicHttpbinding w/ SOAP message and a DataContract. 这是我用来连接WCF服务的简单JavaScript ping函数-带SOAP消息的basicHttpbinding和DataContract。 From something like this, you should be able to adapt to your own requirements. 通过这样的事情,您应该能够适应自己的需求。

<script type="text/javascript">
function Ping() {             
  //set up varable
   var sContent;
   sContent=  "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><a:TextSection><Method>ping</Method></a:TextSection><a:BodySection>AA==</a:BodySection></s:Body></s:Envelope>";

  var xmlhttp =  new XMLHttpRequest();
  xmlhttp.open('POST', Demo.URL.value, true);  

  //    alert(Demo.URL.value);
  xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4||xmlhttp.readyState == 0) {
    //alert("Ready state: " + xmlhttp.readyState.toString());
    if (xmlhttp.status == 200) {
        //alert("good");
        Demo.pingresponse.value = "Response: " +xmlhttp.responseText;
    }
        if (xmlhttp.status !=200){
            //alert("bad");
            Demo.pingresponse.value = "Error: " +xmlhttp.status.toString() +"  response text:  " +xmlhttp.responseText;
        }
    } else {
       //alert("readystate bad");
    }
}
//send request    
        xmlhttp.setRequestHeader("POST http:localhost:8085/ServiceClass/ServiceMethod HTTP/1.1"); 
        xmlhttp.setRequestHeader("VsDebuggerCausalityData","iEA8ACQAA"); 
        xmlhttp.setRequestHeader("SOAPAction","\"http://NameSpace\""); 
        xmlhttp.setRequestHeader("Host","localhost:8085"); 
        xmlhttp.setRequestHeader("Expect","100-continue"); 
        xmlhttp.setRequestHeader("Accept-Encoding","gzip, deflate"); 
        xmlhttp.setRequestHeader("Connection","Keep-Alive"); 
        xmlhttp.setRequestHeader("Content-Length","639");                   
        xmlhttp.setRequestHeader("Content-type", "text/xml; charset=utf-8"); 
        xmlhttp.send(sContent);                  
}
</Script>

We have found the solution and is given below. 我们找到了解决方案,并在下面给出。

http://www.bendewey.com/index.php/186/using-jsonp-with-wcf-and-jquery http://www.bendewey.com/index.php/186/using-jsonp-with-wcf-and-jquery

Asp page ASP页面

<script type="text/javascript">
    $(document).ready(function () {

        $('#getCustomers').click(function () {
            var $customersList = $('#customersList');
            $customersList.empty().appendLi('Loading...');
            // Get the JsonP data  $.getJSON('http://localhost:65025/CustomersService.svc/GetCustomers?callback=?', { id: '25' }, function (customers) {
                alert('Received ' + customers.length + ' Customers');

                alert("data -" + JSON.stringify(customers.toString()));
                $customersList.empty();
                $.each(customers, function () {
                    $customersList.appendLi(this.Name + " - " + this.Email);
                });
            });
        }); // end #getCustomer.click

    });

    (function($) {
        $.fn.appendLi = function(text) {
            /// <summary>
            /// This is a simple helper plugin on top of the append() function that allows you to quickly add a li
            ///     element with text.
            /// </summary>
            return $(this).each(function() {
                $(this).append($('<li />').text(text));
            });
        };
    })(jQuery);

Web.config in WCF hosted place WCF托管位置中的Web.config

<bindings>

  <webHttpBinding>
    <binding name="webHttpBindingWithJsonP"         crossDomainScriptAccessEnabled="true" />
  </webHttpBinding>

</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
  multipleSiteBindingsEnabled="true" />

<services>

  <service name="CustomersService">
    <endpoint address="" behaviorConfiguration="CustomersServiceAspNetAjaxBehavior"
      bindingConfiguration="webHttpBindingWithJsonP" binding="webHttpBinding" contract="IAT.Web.Services.CustomersService" />
  </service>

  <service name="ServiceSite.CustomersService">
  </service>

</services>

CustomersService.svc CustomersService.svc

  [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    public string Display(int id)
    {
        string[] s = new string[3];
        for (int i = 0; i < 3; i++)
        {
            s[i] = i + "*" + (i + 1) + "*" + (i + 2);
        }

        return string.Format(id.ToString());

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM