[英]get data from ajax with POST
right now I am stuck on a problem. 现在,我陷入了一个问题。 I guess it is a very basic thing.
我想这是非常基本的事情。 But after doing researches for hours it would be great if someone can give me a quick advice.
但是经过数小时的研究,如果有人可以给我快速建议,那就太好了。 So I am trying to call my PUT method from my api (C#)
所以我试图从我的api(C#)调用我的PUT方法
[HttpPost]
public String Post(String id)
{
return id;
}
It is called when i press a button. 当我按下一个按钮时,它被称为。 The button function is this:
按钮功能是这样的:
<script>
function sendData() {
$.ajax({
url: '/api/values',
type: 'POST',
data: {'id':"100014"},
dataType: 'json',
contentType: 'application/json',
});
}
If I call the GET method everything works fine. 如果我调用GET方法,一切正常。 But trying to call the POST method it only returns that the resource is not supported for HTTP Post.
但是尝试调用POST方法只会返回HTTP Post不支持该资源。 I tested the method with Postman.
我用邮递员测试了该方法。 Here the Post method works.
在这里,Post方法有效。 But I do not want to pass these data into the Url but into the data from Ajax.
但是我不想将这些数据传递给Url,而是传递给Ajax的数据。
It would be great if someone can help me out. 如果有人可以帮助我,那就太好了。
EDIT: I just tried some stuff. 编辑:我只是尝试了一些东西。 My final result is this:
我的最终结果是:
[HttpPost]
public async Task<IHttpActionResult> Post(int id)
{
var rawMessage = await Request.Content.ReadAsStringAsync();
return Ok(rawMessage);
}
It worked out for me fine. 它对我来说很好。
Problem is that you route is not found. 问题是找不到您的路由。 Try
尝试
[HttpPost]
[Route("getValues")]
public String Post(String id)
{
return id;
}
You can even add before controller class: 您甚至可以在控制器类之前添加:
[RoutePrefix("api/values")]
and then call it with 然后用
url: '/api/values/getValues',
Please check if you referenced the correct library. 请检查您是否引用了正确的库。
If you're using System.Web.Mvc
this issue might occur. 如果您使用的是
System.Web.Mvc
则可能会出现此问题。 Trying removing that and referencing System.Web.Http
instead. 尝试将其删除,然后引用
System.Web.Http
。
Hope this solves your issue. 希望这能解决您的问题。
You should wrap your output with Ok()
method . 您应该使用
Ok()
方法包装输出。 Something like 就像是
Use your returm type as IHttpActionResult
使用您的
IHttpActionResult
类型作为IHttpActionResult
[HttpPost]
public IHttpActionResult Post(String id)
{
return Ok(id);
}
You should convert a JavaScript object to a string with JSON.stringify(). 您应该使用JSON.stringify()将JavaScript对象转换为字符串。 You can modify your method in script like this.
您可以像这样修改脚本中的方法。
<script>
function sendData() {
var obj = { id:'100014'};
$.ajax({
url: '/api/values',
type: 'POST',
data: JSON.stringify(obj),
dataType: 'json',
contentType: 'application/json',
success: function(data) {
alert(data);
}
});
}
</script>
By the way, I see your path is incorrect. 顺便说一句,我看到您的路径不正确。 It should be
/api/post
它应该是
/api/post
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.