[英]Calling a ASP.net WebMethod from the success function of another WebMethod
[英]Ajax Call in Asp.net ([WeBMethod] Function not calling)
我正在開發一個相當大的應用程序。 但是我在 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]。 任何人都知道問題所在。
使您的[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);
}
});
});
});
您是否嘗試過為您的方法設置 ScriptMethod 屬性,如下所示:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
這是工作
C#
[WebMethod]
public static string Test(string str)
{
return str;
}
JS
const text = "this is test";
$.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); }
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.