【问题标题】:Ajax using JQuery in ASP .NET c#在 ASP .NET c# 中使用 JQuery 的 Ajax
【发布时间】:2016-01-25 17:18:30
【问题描述】:

我正在尝试在 asp .net c# 中使用 JQuery ajax。我使用的代码是...

HTML 表格:

<div>
    Your Name :
    <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
    <input id="btnGetTime" type="button" value="Show Current Time"
     onclick = "ShowCurrentTime()" />
</div>

JQuery 部分:

<script type="text/javascript">
    function ShowCurrentTime() {
        //alert(window.location.pathname);
        $.ajax({
            type: "POST",
            url: "Display.aspx/GetCurrentTime",
            data: '{name: "' + $("#< %=txtUserName.ClientID%>")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function (response) {
            alert(response.d);
        }
    });
}
function OnSuccess(response) {
    alert(response.d);
}
</script>

CS部分:

    using System.Web.Services;

    This part below is under partial class which inherits from Page class.

   [WebMethod]

    public static string GetCurrentTime(string name)
    {

     return "Hello "+ name +"! " + Environment.NewLine + "The Current Time is: "
            + DateTime.Now.ToString();
    }

问题: 它不工作。如果我缺少任何设置或任何名称空间,请告诉我。或者任何东西。我在 ajax 调用中输入的 URL 是正确的,因为我通过以下方式验证了它 var pathname = window.location.pathname;我在调用 ajax 时也提供了数据。

【问题讨论】:

  • 你有没有 jquery.unobtrusive-ajax.min.js
  • 是否有任何东西返回到服务器。加载工具 Fiddler 以确保您可以看到发出的请求。将其缩小到客户端或服务器,以便我们帮助排除故障。
  • 什么不起作用?我们可以看看你的控制台吗?
  • @Stralos 我可以看到控制台。没有来自任何地方的电话。
  • @HerGiz 我认为此调用不需要 jQuery.unobstrustive-ajax.min.js。

标签: c# jquery asp.net ajax asp.net-ajax


【解决方案1】:

也许会改变

 failure: function (response) {
        alert(response.d);
    }

 error: function (response) {
        alert(response.d);
    }

将帮助找到问题。 我在文档中没有看到失败回调 - http://api.jquery.com/jquery.ajax/

【讨论】:

  • 谢谢。将失败更改为错误后,它开始工作。 :)
【解决方案2】:

我马上就能看到的东西:

  1. $.ajax 不采用“失败”参数,而是采用“错误”。甚至 那么,您应该改用 .done() 和 .fail() (请参阅 http://api.jquery.com/jQuery.ajax/)
  2. 你的错误处理函数会在你的页面方法被触发 抛出异常。第一个参数是一个 jqXHR 对象,而不是一个 来自 .NET 的 JSON 响应(参见与 #1 相同的链接)。
  3. 您的页面方法不应位于页面类之下,而应位于其中。

【讨论】:

    【解决方案3】:

    JQuery 有一些错误

        $("#< %=txtUserName.ClientID%>")[0].value
    

    需要

        $("#<%=txtUserName.ClientID%>")[0].value
    

        $("#<%=txtUserName.ClientID%>").val() 
    

    【讨论】:

    • 谢谢。但是这里的空间是错误的。在我的程序中,它与您建议的相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    • 2018-05-06
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多