Ajax 以Post 方式 访问 WebAPI 服务

第一种服务方法 [FromBody]string  单值参数

 1 [HttpPost]
 2         public string PostWebNameOne([FromBody]string para)
 3         {
 4             Dictionary<string, string> dict = new Dictionary<string, string>();
 5             
 6             dict.Add("测试",para);
 7           
 8             return Tools.ConvertToJsonStr(dict);
 9 
10         }

JQuery 调用方式

 1 $.ajax({
 2                 type: "post",
 3                 dataType: 'json',//服务器返回json格式数据
 4                 //contentType: 'application/json',//如果是针对[FromBody]string 参数  contentType 需要注释掉,不然会接收不到值
 5                  
 6                 headers: { Authorization: "lzsin" },
 7 
 8                 url: "http://localhost:10450/api/EmpInfo/PostWebNameOne",
 9                data: { "": "参数值" },
10               
11 
12                 success: function (data, response, status) {
13 
14                     alert(data);
15 
16                 },
17                 error: function (data) {
18                     console.log(data);
19                     alert('失败!' + data["responseText"]);
20                   
21                 }
22 
23             });

第二种服务方法 传递实体或对象

 1 [AllowAnonymousAttribute]
 2         [HttpPost]
 3         public string PostWebName(dynamic login)
 4         {
 5             Dictionary<string, string> dict = new Dictionary<string, string>();
 6             dict.Add("姓名", Convert.ToString(login.name));
 7             dict.Add("密码", Convert.ToString(login.pwd));
 8 
 9             return Tools.ConvertToJsonStr(dict);
10 
11         }

JQuery 调用方式

 1 $.ajax({
 2                 type: "post",
 3                 dataType: 'json',//服务器返回json格式数据
 4                  contentType: 'application/json',//如果是针对[FromBody]string 参数  contentType 需要注释掉,不然会接收不到值
 5                  url: "http://localhost:10450/api/EmpInfo/PostWebName",
 6                 data: JSON.stringify({ name: "用户名", pwd: "用户密码" }),
 7                 headers: { Authorization: "lzsin" },
 8                 success: function (data, response, status) {
 9 
10                     alert(data);
11 
12                 },
13                 error: function (data) {
14                     console.log(data);
15                     alert('失败!' + data["responseText"], data, 'warning');
16                   
17                 }
18 
19             });
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xinyuan178

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值