代碼如下 |
複製代碼 |
using jquery ajax call wcf service get/post/put/delete http://www.codeproject.com/Articles/254714/Implement-CRUD-operations-using-RESTful-WCF-Servic Using POST Method Retrieve a representation of the addressed member of the collection, in the example below, create a new entry in the collection. Collapse | Copy Code $.ajax({ type: "POST", url: "Services/EFService.svc/Members/", data: "{Email:'test@test.com', ScreenName:'TestUser'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { // Play with response returned in JSON format }, error: function (msg) { alert(msg); } }); Using PUT Method Update the entire collection with another collection, in the example below, update the addressed member of the collection. Collapse | Copy Code $.ajax({ type: "PUT", url: "Services/EFService.svc/Members/", data: "{Email:'test@test.com', ScreenName:'TestUser'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { // Play with response returned in JSON format }, error: function (msg) { alert(msg); } });Using DELETE Method Delete the entire collection or a specific collection, in the example below, delete Member with id=1. Collapse | Copy Code $.ajax({ type: "DELETE", url: "Services/EFService.svc/Members(1)", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { // Play with response returned in JSON format }, error: function (msg) { alert(msg); } }); |
jQuery ajax跨域調用WCF服務
以下是契約層介面:
代碼如下 |
複製代碼 |
namespace Valor.ValorCom.Contracts { [ServiceContract(Name = "NAVService", Namespace = "www.valorcomm.com")] public interface INAVService { /// <summary> /// 添加訂單 /// </summary> /// <param name="orderId">訂單號</param> /// <returns></returns> [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] string AddOrderForNAV(int orderId); } } |
第一點要注意的:指定服務可以通過GET方式調用,佈建要求和響應的格式都是JSON.
以下是服務類:
代碼如下 |
複製代碼 |
namespace Valor.ValorCom.Services { [AspNetCompatibilityRequirements( RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")] public class NAVService : INAVService { public NAVService() { } /// <summary> /// 添加訂單 /// </summary> /// <param name="orderId">訂單號</param> /// <returns></returns> public string AddOrderForNAV(int orderId) { string result = ""; if (Common.TurnNav()) { //添加訂單相關代碼 } else { result = "未開啟與NAV系統同步訂單的介面"; } return result; } } }
|
第二點要注意的,一定要加上[JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")],為javascript回調使用,UrlParameterName 設定用於跨域指令碼訪問的 URL 查詢字串參數名稱。[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 用於asp.net管道相容,這樣的話此服務可以通過jquery ajax跨域調用,asp.net程式也可以通過產生此服務的代理來調用. 以下是設定檔資訊
代碼如下 |
複製代碼 |
<?xml version="1.0"?> <configuration> <system.web> <compilation debug="true"/> </system.web> <appSettings> </appSettings> <system.serviceModel> <behaviors> <endpointBehaviors> <behavior name="webBehavior"> <!--這裡必須設定--> <!--<webHttp />--> <enableWebScript /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="navMetadataBehavior"> <serviceMetadata httpGetEnabled="true" httpGetUrl="http://wcf.9valor.com/NAVService.svc/metadata"/> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="navMetadataBehavior" name="Valor.ValorCom.Services.NAVService"> <endpoint binding="webHttpBinding" address="http://127.0.0.1:90/NAVService/web" behaviorConfiguration="webBehavior" bindingConfiguration="webBinding" contract="Valor.ValorCom.Contracts.INAVService" /> <endpoint address="http://127.0.0.1:90/NAVService" binding="basicHttpBinding" contract="Valor.ValorCom.Contracts.INAVService"></endpoint> </service> </services> <bindings> <webHttpBinding> <binding name="webBinding" crossDomainScriptAccessEnabled="true"> </binding> </webHttpBinding> </bindings> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true"> <baseAddressPrefixFilters> <add prefix="string"/> </baseAddressPrefixFilters> </serviceHostingEnvironment> </system.serviceModel> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> </configuration> |
第三點注意:
代碼如下 |
複製代碼 |
<service behaviorConfiguration="navMetadataBehavior" name="Valor.ValorCom.Services.NAVService"> <endpoint binding="webHttpBinding" address="http://www.111cn.net/n96/ NAVService/web" behaviorConfiguration="webBehavior" bindingConfiguration="webBinding" contract="Valor.ValorCom.Contracts.INAVService" /> <endpoint address="http://127.0.0.1:90/NAVService" binding="basicHttpBinding" contract="Valor.ValorCom.Contracts.INAVService"></endpoint> </service>
|
這裡配置了兩上終結點,第一個終結點的配置給jquery ajax以web的形式調用該服務,指定該終結點的綁定為webHttpBinding,我們看下behaviorConfiguration的配置,
behaviorConfiguration="webBehavior",如下圖配置,<enableWebScript /> 配置指定允許web指令碼訪問。
代碼如下 |
複製代碼 |
<endpointBehaviors> <behavior name="webBehavior"> <!--這裡必須設定--> <!--<webHttp />--> <enableWebScript /> </behavior> </endpointBehaviors>
|
接下來我們再看下bindingConfiguration的配置,bindingConfiguration="webBinding",詳細配置如下圖,crossDomainScriptAccessEnabled指定指令碼可以跨域訪問.
代碼如下 |
複製代碼 |
<webHttpBinding> <binding name="webBinding" crossDomainScriptAccessEnabled="true"> </binding> </webHttpBinding>
|
第二個終結點的配置提供給asp.net通過服務代理的方式調用.
最後就是用戶端調用(注:GET方式在各瀏覽器下都正常,POST方式只有在IE下能通過,其它瀏覽器因為安全原因拒絕跨域POST提交)
代碼如下 |
複製代碼 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script> <script type="text/javascript"> $(function () { $("#btnExcute").click(function () { var url = $("#txtServiceUrl").val(); url += "&orderId="+$("#txtOrderId").val(); $.ajax({ type: "get", dataType: "json", url: url, success: function (returndata) { alert(returndata); } }); }); }); </script> </head> <body> <h2> 修改單個產品 </h2> <p> Wcf Service Url:<input type="text" style="width: 700px;" id="txtServiceUrl" name="txtServiceUrl" value="http://127.0.0.1:90/AspNavService/web/AddOrderForNAV?jsoncallback=?" /> </p> <p> Order Id:<input type="text" id="txtOrderId" name="txtOrderId" value="11665369" /> <br /> <input type="button" id="btnExcute" name="btnExcute" value="修改" /> </p> </body> </html> |