2015-09-01 51 views
2

我正在开发一个相当大的应用程序。但是我在Ajax中遇到了问题。为此,我试图制作一个新的简短程序来调用Ajax进行测试。但我陷入困境。 这里是Test.aspx的代码在Asp.net中调用Ajax([WeBMethod]函数不能调用)

<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); 
    } 

当我在文本框把一些价值。它警告是!但不调用[WebMethod]。 任何人都知道这个问题。

+0

我改为静态。但问题依然存在。 –

+1

而不是'Console.WriteLine(str);'使用'return str;'然后'alert(data)'成功回调 –

回答

2

让您[WebMethod]静如

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

变化AJAX数据值data: "{'str':'" + text + "'}"

UPDATE 尝试相同的代码 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

数据类型应该是dataType:“json” –

+1

将Console.Writeline更改为某些变量或返回类型,检查我的编辑^ –

1

你有没有尝试设置ScriptMethod属性为你的方法,像这样:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
+1

是的,我已经尝试过。我被困在这个代码三天。 –

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); } 
});