Asp.net中的Ajax调用([WeBMethod]函数未调用)

本文关键字:调用 函数 WeBMethod net 中的 Ajax Asp | 更新日期: 2023-09-27 18:10:44

我正在开发一个相当大的应用程序。但是我在Ajax中遇到了问题。为此,我尝试编写一个新的短程序来调用Ajax以进行测试。但我深陷其中。下面是测试。aspx代码

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Testing</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="test.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
            <asp:Button ID="Button1" runat="server" Text="Button" />
        </div>
    </form>
</body>
</html>

Ajax函数

$(document).ready(function () {
$("#Button1").click(function () {
    var text = $("#TextBox1").val();
    text = "this is test";
    debugger
    $.ajax({
        type: "POST",
        contentype: "application/json; charset=utf-8",
        url: "Test.aspx/Test",
        data: { str: text},
        //dataType:"json",
        success: function (data) {
            alert("yes");
        },
        error: function (response) {
            debugger
            alert(response);
        }
    });
    return false;
});
});

Test.aspx.cs代码在

下面
[WebMethod]
    public void Test(string str)
    {
        Console.WriteLine(str);
    }

当我在TextBox中添加一些值时。它提醒Yes!但是不调用[WebMethod]。有谁知道问题所在吗?

Asp.net中的Ajax调用([WeBMethod]函数未调用)

[WebMethod]设置为静态

[WebMethod]
    public static void Test(string str)
    {
        //Console.WriteLine(str);
        string retstr=str;
    }

更改ajax数据值为data: "{'str':'" + text + "'}"

试试同样的代码aspx:

<asp:Button ID="Button1" ClientIDMode="Static" runat="server" Text="Button" />

aspx.cs

    [WebMethod]
    public static void Test(string str)
    {
        string abc=str;//Use this wherever you want to, check its value by debugging
    }

. js

$(document).ready(function () {
$("#Button1").click(function () {
    var text = "this is test";
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Test.aspx/Test",
        data: "{'str':'" + text + "'}",
        dataType:"json",
        success: function (data) {
            alert("yes");
        },
        error: function (response) {
            alert(response);
        }
    });
   });
});

正常运行

c#

[WebMethod]
public static string Test(string str)
{
      return str;
}

JS

const text = "this is test";   
$.ajax({      
      url: "Test.aspx/Test",
      contentType: "application/json; charset=utf-8",
      method: 'post',
      data: "{'str':'"+text+"'}",
      success: function (data) {
               console.log(data);},
      error: function (response) {
               debugger;
               console.log(response);  }
});

您是否尝试过为您的方法设置ScriptMethod属性:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]