Server:
[ServiceContract (Namespace = "")] [AspNetCompatibilityRequirements (RequirementsMode = AspNetCompatibilityRequirementsMode. allowed)] [JavascriptCallbackBehavior (UrlParameterName = "jsoncallback")] public class Service2 {// Add the [WebGet] attribute to use http get [OperationContract]
// [WebGet] public void DoWork () {// Add the operation here to implement return;} [OperationContract] // [WebGet] [WebInvoke (Method = "GET ", bodyStyle = WebMessageBodyStyle. wrappedRequest, ResponseFormat = WebMessageFormat. json, RequestFormat = WebMessageFormat. json)] public string GetName (string name) {// Add the operation here to implement return "hello:" + name ;}
Note the following two sentences:
[JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")]
[WebInvoke (Method = "GET", BodyStyle = WebMessageBodyStyle. WrappedRequest, ResponseFormat = WebMessageFormat. Json, RequestFormat = WebMessageFormat. Json)]
Server Configuration File
Configure:
<webHttpBinding> <binding name="webBinding" crossDomainScriptAccessEnabled="true"/> </webHttpBinding>
<service name="Service" > <endpoint address="" bindingConfiguration="webBinding" behaviorConfiguration="Service2AspNetAjaxBehavior" binding="webHttpBinding" contract="Service2"/> </service>
WebSite Configuration:
AJAX calls WCF:
First, reference the published service address to obtain the JS
Http: // 192.168.1.159: 8080/Service2.svc/js
// Reference 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 calls 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()" />
Attachment download