服務端:
[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()" />
附件下載