使用JQuery调用Web Api操作

时间:2014-10-06 22:58:49

标签: jquery asp.net-web-api

我有以下JQuery:

$(document).ready(function () {
  $("#send").on("click", function () {
    $.ajax({
      url: 'http://localhost:3484/api/mail/send/',
      type: 'POST',
      dataType: 'text',
      data: 'some_email@test.com'
    });
  });
});

Web API操作是:

[Route("api/mail/send"), HttpPost]
public void Send([FromBody]String email) {
}

调用该操作但电子邮件为空。

我错过了什么?

2 个答案:

答案 0 :(得分:1)

这应该有效

$(document).ready(function () {

  $("#send").on("click", function () {
    var data={email :'some_email@test.com'};

    $.ajax({
      url: 'http://localhost:3484/api/mail/send/',
      type: 'POST',
      contentType : 'application/json',
      data:  JSON.stringify(data)
    });

  });

});

答案 1 :(得分:0)

$(document).ready(function () {
  $("#send").on("click", function () {
    $.ajax({
      url: 'http://localhost:3484/api/mail/send/',
      type: 'POST',
      dataType: 'text',
      data: { email: `some_email@test.com' },
    });
  });
});

data必须是JSON对象。 $.ajax的替代方案是$.post。它有文档:http://api.jquery.com/jquery.post/