ASP.NET 可视化 Web 部件 + AJAX,无法正常工作

Posted

技术标签:

【中文标题】ASP.NET 可视化 Web 部件 + AJAX,无法正常工作【英文标题】:ASP.NET visual web part + AJAX, can't make it working 【发布时间】:2017-04-02 01:58:39 【问题描述】:

我试图实现这个简单的例子http://www.aspsnippets.com/Articles/Call-ASPNet-Page-Method-using-jQuery-AJAX-Example.aspx

但它不起作用,它给了

Failed to load http://site/path/path/pagename.aspx/GetCurrentTime resource: the server responded with a status of 500 (Internal Server Error)

客户端

<script src="http://.../jquery-1.7.2.min.js" type="text/javascript"></script>
<script type = "text/javascript">
    function ShowCurrentTime() 
        $.ajax(
            type: "POST",
            url: "pagename.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>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
    onclick = "ShowCurrentTime()" />

服务器(.cs 文件)

        [System.Web.Services.WebMethod]
        public static string GetCurrentTime(string name)
        
            return "Hello " + name + Environment.NewLine + "The Current Time is: "
                + DateTime.Now.ToString();
        

【问题讨论】:

【参考方案1】:

ajax 定义中没有failure 这样的函数。您需要将其重命名为error。查看来源:jQuery.ajax()

P.S 我还建议您使用console.log,而不是警报。 console.log你的name参数,看看是否返回正确的值。检查 JSON.stringify 以创建您的数据。

【讨论】:

是的,现在错误只返回“未定义”。但我仍然无法理解问题出在哪里。我在调试,没有调用服务器方法。 @HoTTab1CH 我想你的数据有问题。在而不是你的 jquery 代码中编写简单的字符串。 我做了,同样的错误。也许应该在服务器端添加其他东西?

以上是关于ASP.NET 可视化 Web 部件 + AJAX,无法正常工作的主要内容,如果未能解决你的问题,请参考以下文章

jQuery ajax 在 Sharepoint 可视化 Web 部件中不起作用

Sharepoint:Web 部件与 ASP.NET 用户控制

在 ASP.NET 中开发 SharePoint Web 部件 [关闭]

ASP.NET 按钮不呈现 ID - Sharepoint Web 部件

Web 部件区域标题在 ASP.NET 中显示 Untitled[0]

ASP.NET Web 部件:非 IE 浏览器中的拖放支持