以下所示(示例):web
namespace WCF_Ajax跨域調用示例 { [ServiceContract(Namespace = "WCF_Ajax跨域調用示例")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")] public class WCFAjaxService { [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json)] public List<UserInfo> GetUser() { return new List<UserInfo>(){ new UserInfo(){Id=1,Name="jayjay1"},new UserInfo(){Id=2,Name="jayjay2"}}; } } [DataContract] public class UserInfo { [DataMember] public int Id { get; set; }
[DataMember]
public string Name { get; set; } } }
注意別忘了給Service打上ajax
[JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")]json
標記。跨域
<system.serviceModel> <bindings> <webHttpBinding> <binding name="HttpJsonBinding" crossDomainScriptAccessEnabled="true"></binding> </webHttpBinding> </bindings> <behaviors> <endpointBehaviors> <behavior name="AjaxServiceAspNetAjaxBehavior"> <enableWebScript /> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/> <services> <service name="AjaxService"> <endpoint address="" behaviorConfiguration="AjaxServiceAspNetAjaxBehavior" binding="webHttpBinding" bindingConfiguration="HttpJsonBinding" contract="AjaxService" /> </service> </services> </system.serviceModel>
注意,配置文件中添加了jsonp
<bindings> <webHttpBinding> <binding name="HttpJsonBinding" crossDomainScriptAccessEnabled="true"></binding> </webHttpBinding> </bindings>
節點,並在endpoint節點中添加了網站
bindingConfiguration="HttpJsonBinding"ui
在另外一個網站中使用url
$.ajax({ url: "http://localhost:46318/WCFAjaxService.svc/GetUser?jsoncallback=?", type: "get", dataType: "jsonp", success: function (data) { alert(data[0]); } });
調用。spa
從返回報文中能夠看出數據以jsonp格式跨域返回。code
jsonp1430098026913([{"__type":"UserInfo:#WCF_Ajax%E8%B7%A8%E5%9F%9F%E8%B0%83%E7%94%A8%E7%A4%BA%E4%BE%8B","Id":1,"Name":"jayjay1"},{"__type":"UserInfo:#WCF_Ajax%E8%B7%A8%E5%9F%9F%E8%B0%83%E7%94%A8%E7%A4%BA%E4%BE%8B","Id":2,"Name":"jayjay2"}]);
data[0]指的是取第一個json對象,如 data[0].Name取到「jayjay1」 。