我正在尝试使用 jquery ajax 调用来使用数据服务功能,我尝试了很多调用它的方法,并设置了服务合同和数据服务,但不管它一直给我 XML 是什么。我听有人说我需要使用jsonp,但这真的有必要吗?
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
这是我的数据服务类
public class MyService : DataService<MyEntities>
{
private readonly MyEntities _dataSource;
public MyService() : this(new MyEntities()) { }
// im doing DI since I am testing my service operations with a local DB
public MyService(MyEntities dataSource)
{
_dataSource = dataSource;
}
protected override MyEntities CreateDataSource()
{
return _dataSource;
}
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("Teams", EntitySetRights.AllRead);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
}
}
这是jquery ajax。它只警告错误,当我在控制台中检查错误时,它是一个 json 解析错误,因为它正在获取 XML。
var url = "http://localhost:2884/MyService.svc/Teams";
$.ajax({
type: "GET",
url: url,
contentType: 'application/json; charset=utf-8',
accept: 'application/json',
dataType: 'json',
success: function (msg) {
alert(msg.d);
},
error: function(xhr, ajaxOptions, thrownError) {
alert("error : " + xhr + ajaxOptions + thrownError);
}
});