WCF Data Service with OData 是一個優秀的Restful Web Service在ASP.NET下的實現,可是在使用中,我遇到了一個問題,即當我單獨部署WDS服務的時候,Ajax訪問就須要跨域。json
在通常的WCF服務中,咱們能夠用JSONP解決。因此我發起了下面這個請求:跨域
你能夠看到響應的ContentType是application/json,因此瀏覽器拋出了一個異常瀏覽器
Refused to execute script from 'http://***.svc/Companies?$filter=Type%20eq%201&$for…on&jsoncallback=jQuery1102003060379653130041_1465881447794&_=1465881447795' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.app
加粗的部分告訴咱們,application/json類型不可執行。JSONP要求回傳類型爲application/json-p或者text/json-pide
可是WDS服務的響應類型只支持Atom、XML和JSON,並不支持JSONP。函數
最終,在MSDN上看到了一篇Blog,其中有一段:ui
There are two things needed to support JSONP properly:orm
- The ability to control the response format. Data Services uses standard HTTP content type negotiation to select what representation of a given resource should be sent to the client (e.g. JSON, Atom). That requires that the caller can set the Accept request header, which is not possible when doing the JSONP trick (which basically just uses <script> tags). We need to add the ability to use the query string in the URL to select format. (e.g. /People(1)/Friends?$orderby=Name&$format=json).
- A new option to wrap the response in a callback if such callback was provided in the request (also in the query string). For example /People(1)/Friends?$orderby=Name&$format=json&$callback=loaded.
也就是說只要$format=json而且用$callback定義回調函數就能夠了blog
成功獲取數據。~~ip