我想将一些数据发布到API控制器并接收响应,如失败或接受我的控制器
public HttpResponseMessage Post([FromBody]Person person)
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
以及将Person数据发送到My API的前端代码是
function myfunc() {
$(function () {
var person = {'id':"1",'Name':"Mohammad",FamilyName:"Basiri"};
//preventDefault();
$.ajax({
type: "POST",
//contentType: "application/json",
data: (person),
url: "http://localhost:40027/api/Person",
dataType: 'json',
//contentType: "application/json",
success: function (d) {
alert("Done");
},
error: function (result) {
var e = JSON.stringify(result);
alert(e);
}
});
});
,收到的状态代码为200 OK 但是JQuery Function会触发错误 如果使用我评论的内容类型,则无法发送Person 我的问题是我可以做些什么来向JQuery发送一个响应,它接收它是正确的并且不会触发错误?
提前致谢
答案 0 :(得分:0)
$(function () {
var person = {id: "1", Name: "Mohammad", FamilyName: "Basiri"};
$.ajax({
type: "POST",
data :JSON.stringify(person),
url: "api/Person",
contentType: "application/json"});
});
从示例中获取并修改...首先尝试,然后在
中添加您的成功和错误方法答案 1 :(得分:0)
我没有准确地告诉你你想说的是什么,但尝试下面的方法它可能对你有帮助。
- 谢谢
$.ajax({
type: "POST",
headers:{ contentType: 'application/json' },
data: {person:person},
url: 'http://localhost:40027/api/Person',
cache:false,
success: function (d) {
alert("Done");
},
error: function (jqXHR) {
alert(jqXHR.statusText);
}
});
答案 2 :(得分:0)
if you are using HttpResponseMessage(HttpStatusCode.OK) then in
ajax dataType:'text' should be as
第二种方式
You can use HttpResponseMessage(HttpStatusCode.Created) then in
ajax dataType:'text' should be as
ajax的例子
$.ajax({
type: 'POST',
url: baseUrl + 'api/CompanyInfo', //path of api
contentType: "application/json", // send to server, json data
dataType: "text", //receive from server
async: true, //
traditional: true,
data: JSON.stringify(json), //contentType is json, so i have converted data into json
success: function (data, status, jqXHR) {
if (jqXHR.statusText = 'OK' && jqXHR.status == 200) {
ShowMessage("Update Successfully", 'Success');
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
ShowMessage(XMLHttpRequest.responseText, 'Error');
}
});