我正在开发一个非常大的应用程序。但我在Ajax面临问题。为此,我尝试创建一个新的简短程序来调用Ajax用于测试目的。但我陷入了困境。 这是Test.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中放入一些值时。它提醒是的!但是没有调用[WebMethod]。 任何人都知道这个问题。
答案 0 :(得分:2)
将[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
}
test.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);
}
});
});
});
答案 1 :(得分:1)
您是否尝试过为您的方法设置ScriptMethod属性,如下所示:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
答案 2 :(得分:1)
这是有效的
C#
[WebMethod]
public static string Test(string str)
{
return str;
}
JS
$.ajax({
url: "Test.aspx/Test?str="+text,
contentType: "application/json; charset=utf-8",
method: 'post',
data: "{'str':'"+text+"'}",
success: function (data) {
console.log(data);},
error: function (response) {
debugger;
console.log(response); }
});