WCF Ajax、Jquery跨域访问

服务端:

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")]
public class Service2
{
	// 添加 [WebGet] 属性以使用 HTTP GET
	[OperationContract]
    //[WebGet] public void DoWork() { // 在此处添加操作实现 return; }     [OperationContract]     //[WebGet]     [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]     public string GetName(string name)     {         // 在此处添加操作实现         return "hello:" + name;     }

需要注意的是这两句:

[JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]



服务端配置文件

进行相关配置:
      <webHttpBinding>
        <binding name="webBinding" crossDomainScriptAccessEnabled="true"/>
       </webHttpBinding>  
      <service name="Service" >
	  <endpoint address="" bindingConfiguration="webBinding" behaviorConfiguration="Service2AspNetAjaxBehavior" binding="webHttpBinding" contract="Service2"/>
      </service>
    

WebSite配置:

AJAX调用WCF:

首先引用发布的服务地址获取JS

http://192.168.1.159:8080/Service2.svc/js

   //引用js 

  

    <asp:ScriptManager ID="scriptManager" runat="server">
        <Scripts>
            <asp:ScriptReference Path="~/JS/AjaxServer.js" />
        </Scripts>
    </asp:ScriptManager>
    <script type="text/javascript">        
        function sayhello() {
            var name = $get("txtname").value;
            Service2.GetName(name, onSuccess, onFailed);
        }
        function onSuccess(res) {
            alert(res);
        }
        function onFailed(res) {
            alert(res._message);
        }
    </script>
        <input id="txtname" name ="txtname" type="text" />
        <input id="btnInput" name="btnInput" type="button" value="input" onclick="sayhello()" />

Jquery调用WCF:

   <script type="text/javascript" src="jquery-1.7.2.js"></script>
    <script type="text/javascript">
        function Jquery() { 
        $.ajax({
            type: "get",
            dataType: "json",
            url: 'http://192.168.1.159:8080/Service.svc/GetName?jsoncallback=?',
            data: { name: $get("txtname").value },
            success: function (returndata) {
                alert(returndata);
            }
        });
    }
     </script>

  <input id="txtname" name ="txtname" type="text" />
      
  <input id="btnInput" name="btnInput" type="button" value="input" onclick="Jquery()" />



经查,确实原先代码上传有误,现上传完整代码:
 https://pan.baidu.com/s/1nvNSUed

 
原文地址:https://www.cnblogs.com/midcn/p/2618644.html