上面的改成POST类型
时间: 2023-10-29 10:07:02 浏览: 41
当你想要使用POST类型来进行Ajax异步调用时,你需要做以下更改:
在Web API控制器中:
```csharp
public class MyApiController : ApiController
{
[HttpPost]
public IHttpActionResult GetString([FromBody] string name)
{
string myString = "Hello, " + name + "!";
return Ok(myString);
}
}
```
在JavaScript中:
```javascript
$(document).ready(function () {
var name = "John"; // 替换为你想要传递的参数值
$.ajax({
type: "POST",
url: "api/MyApi/GetString", // 替换为你的Web API路由
data: JSON.stringify(name), // 将参数转换为JSON字符串
contentType: "application/json; charset=utf-8", // 设置Content-Type头为application/json
success: function (response) {
console.log(response); // 在控制台输出返回的字符串
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
```
在上述示例中,我们将参数值作为请求的主体数据进行传递,并使用`JSON.stringify()`方法将参数转换为JSON字符串。同时,我们还设置了`contentType`头为`application/json`,以指示服务器接收的数据类型。
请确保你的Web API控制器方法接受一个名为`name`的参数,并使用`[FromBody]`属性将其绑定到请求主体。
这样,你就可以使用POST类型来进行Ajax异步调用,并将参数传递给Web API方法。