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
 
        
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM