服务
[ServiceContract]
public interface IFoo
{
[OperationContract]
[WebGet(UriTemplate = "/foos/", ResponseFormat = WebMessageFormat.Json]
Foo[] GetFoos();
}
模型
// this is in a separate assembly from the service
[DataContract]
public class Foo
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
}
JQuery
$(document).ready(function() {
$.getJSON(fooUrl, function(data) {
alert(data); // data is an object, but data.items is null
// this complains 'length is null or not an object'
$.each(data.items, function(i, item) {
fooList.append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
});
});
});
当我看到Fiddler中的响应时,我看到:
[{"Id":1,"Name":"Foo1"},{"Id":2,"Name":"Foo2"},{"Id":3,"Name":"Foo3"}]
更新
以下是来自fiddler的原始标题,用于响应比较(me与flickr)
矿
HTTP/1.1 200 OK
Content-Length: 162
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Flickr
HTTP/1.1 200 OK
Date: Sat, 12 Dec 2009 00:30:36 GMT
P3P: policyref="http://p3p.yahoo.com/w3c/p3p.xml", CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV"
Expires: Mon, 26 Jul 1997 05:00:00 GMT
Last-Modified: Sat, 12 Dec 2009 00:26:19 GMT
Cache-Control: no-store, no-cache, must-revalidate
Cache-Control: post-check=0, pre-check=0
Pragma: no-cache
Vary: Accept-Encoding
Connection: close
Transfer-Encoding: chunked
Content-Type: application/x-javascript; charset=utf-8
看起来最大的区别是我有application/json,他们有application/x-javascript。如上所述,我在操作合同中使用WebMessageFormat.Json。
谢谢你的帮助。