c# - 无法使用 jquery ajax 调用 aspx 页面 Web 方法

标签 c# javascript jquery asp.net ajax

尝试在 aspx 页面上调用 Web 方法时获取 aspx 页面 html。这是 jQuery 代码

  $(function () {
        $.ajax({
            type: 'POST',
            url: 'Default.aspx/Hello',
            data: "{}",
            async: false,
            success: function (response) {
                console.log('Success: ', response);
            },
            error: function (error) {
                console.log('Error: ', error);
            }
        });
    });

这是网络方法代码

 [System.Web.Services.WebMethod]
    public static string Hello()
    {
        string returnString = "hoiiiiiii";
        return returnString;
    }

任何人都可以指出什么可能是错误的吗?

最佳答案

有两件事:

  1. 您的 jQuery .ajax() 函数中缺少 contentType
  2. 您需要考虑 JSON 响应中的 .d 值。

    $.ajax({
        type: "POST",
        url: "Default.aspx/Hello",
        data: "{}",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            if (result.hasOwnProperty("d")) {
                // The .d is part of the result so reference it
                //  to get to the actual JSON data of interest
                console.log('Success: ', result.d);
            }
            else {
                // No .d; so just use result
                console.log('Success: ', result);
            }
        }
    });
    

Note: The .d syntax was an anti-XSS protection put in by Microsoft in the ASP.NET 3.5 release of ASP.NET AJAX; therefore the check to see if the .d property is there or not.

关于c# - 无法使用 jquery ajax 调用 aspx 页面 Web 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20658042/

相关文章:

c# - 如何在不使用安装程序的情况下在 Windows 8 开始屏幕上放置桌面应用程序快捷方式?

javascript - 比较两个数组的内容

javascript - 单个输入框有 2 个值并将第二个值存储在 php 中

javascript - 如何使用 CSS 类更改特定样式?

jQuery 改变字体系列和字体大小

c# - 在 Entity Framework Core 代码优先的 SQLite 中设置日志模式

c# - 不可发音成员 ''不能像方法一样使用

c# - Visual Studio 2012 测试资源管理器测试正在进行中

javascript过滤器编辑并保存数组

javascript - jQuery 将 UL 与 LI 附加到按钮单击时下拉列表中的值