我想知道在进行ajax调用时是否需要dataType和contentType。我对网络很新,我很困惑。在服务器端,有一个servicestack端点,期望一个具有两个参数的对象,
[DataMember(IsRequired = true)]
public long Id { get; set; }
[DataMember]
public IEnumerable<long> Libraries { get; set; }
所以在我的ajax电话中,我试试这个:
$.ajax({
url: 'bookshelf/' + Id + '/libraries',
type: "POST",
crossDomain: $.support.cors,
data: JSON.stringify(libraryIds),
xhrFields: {
withCredentials: $.support.cors
},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
console.log("success");
当我尝试点击此端点时,我收到400 Bad Request。但是如果我注释掉dataType和contentType:,我会收到500内部服务器错误。我试图理解为什么会这样,以及为了调试为什么我的端点没有被击中而发生了什么。提前谢谢。
答案 0 :(得分:1)
我不确定,如果我可以帮助你的话。我使用以下代码(基于您的示例)
在客户端模型中
public class BookRequest
{
public int Id { get; set; }
public string name { get; set; }
public string author { get; set; }
}
public class LibraryResponse
{
public bool TitleExists{ get; set; }
public int Quantity { get; set; }
}
然后在AppHost.Configure中,我添加了Route
Routes.Add<BookRequest>("/bookshelf/{Id}/libraries", "POST, OPTIONS");
javascript代码
jQuery.support.cors = true;
function BookRequestCall() {
var BookRequest = new Object();
BookRequest.name = "Harry Potter";
var Id = 33;
var LibraryResponse;
$.ajax({
type: 'Post',
contentType: 'application/json',
url: serverIP +'/bookshelf/' + Id + '/libraries',
data: JSON.stringify( BookRequest ),
dataType: "json",
success: function (response, status, xhr) {
LibraryResponse = response;
},
error: function (xhr, err) {
alert(err);
}
});
}
服务方
public LibraryResponse Post(BookRequest request)
{
// request.Id =33 - request.name="Harry Potter" - request.author=null
LibraryResponse response = new LibraryResponse();
response.TitleExists=true;
response.Quantity=10;
return response;
}