无法使用参数调用 ajax 来访问我的 C# 函数

Can't get ajax call with parameters to hit my C# function

Ajax:

var test = "test";

$.ajax(
{
  type: "POST",
  url: "project/function",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  data: { input: test },
  success: function (response) {
    $("#lblMsg").text(response.d);
  },
  failure: function (response) {
    alert(response.d);
  }
});

C# 函数:

[WebMethod]
public void function(string input)
{
}

不带参数连接成功。我尝试了 ajax 调用的 'data' 部分的不同单引号和双引号排列,但无济于事。

我也试过将数据类型设置为 "text",结果类似。

我错过了什么?

我建议您不要将数据作为 JSON 发送。只需删除

contentType: "application/json; charset=utf-8"

和 jQuery 会将数据序列化为正常的 url 编码表单数据格式,这是 WebMethod 所期望的。

尝试这个可能会解决您的问题

var 测试 = "test";

$(document).ready(function () {
   $.ajax({
          type: "POST",
          url: "project/function",
          contentType: "application/json; charset=utf-8",
          datatype: "json",
          data:JSON.stringify({ 'input': test }),
          success: function (response) {
         $("#lblMsg").text(response.d);
  },
  failure: function (response) {
    alert(response.d);
  }
  });
});