【问题标题】:Web method to return simple string using ajax使用ajax返回简单字符串的Web方法
【发布时间】:2018-01-23 13:23:51
【问题描述】:

无法使用 ajax 调用从服务器返回简单字符串。我在 ajax 上没有得到 404,而是 200,statusText: "OK"。

我得到了返回的整页 HTML,它落入了错误块中。

我已编辑配置以包含:

<jsonSerializationmaxJsonLength="2147483647"/>

这是我的 AJAX:

$(function () {
    $.ajax({
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        url: $(location).attr('href') + "/GetYard",
        dataType: "json",
        success: OnSuccess,
        failure: function (response) {
            alert(response.d);
        },
        error: function (response) {
            alert(response.d);
        }
    });
});
function OnSuccess(response) {
    console.log(response);
}

还有我的 VB.Net 代码:

<WebMethod>
Public Shared Function GetYard() As String

    Return "TEST"
    'HttpContext.Current.Response.BufferOutput = True
    'HttpContext.Current.Response.ContentType = "application/json"
    'HttpContext.Current.Response.Write("Test")
    'HttpContext.Current.Response.Flush()
End Function

【问题讨论】:

  • 200 响应代码不会“落入错误块”。你确定这就是正在发生的事情吗?你做了什么调试来确认这一点?如果确实调用了error 回调,那么您得到的不是200
  • @David 当我检查 google chrome 调试器时,我得到 Satus Code: 200 OK 但是错误警报上的断点被击中
  • 如果你设置dataType: "json",并且你的响应不是JSON,错误函数将被调用而不是成功
  • 将方法改为POST
  • @Musa 这行得通,因为它进入了 onsuccess 块,但响应文本是页面 HTML

标签: javascript jquery ajax vb.net asp.net-ajax


【解决方案1】:

这需要在脚本管理器中打开EnablePageMethods 选项:

<asp:ScriptManager .. EnablePageMethods="True" />

如果您阅读了从 onsuccess(参考您的评论)返回的 HTML,它可能是说您需要打开 EnablePageMethods 或其他一些配置选项。

确保已完成;这里也是online example,但您的方法似乎反映了这一点,除了它使用“POST”作为类型而不是“GET”这一事实。

【讨论】:

  • 感谢您的回答,我已经在 Site.Master 中设置了&lt;asp:ScriptManager runat="server" EnablePageMethods="True"&gt;
  • 不幸的是它没有,抱歉我错过了我的回复
  • 您仍然收到 HTML 响应吗?通常包含错误的结果...
猜你喜欢
  • 1970-01-01
  • 2012-12-04
  • 1970-01-01
  • 1970-01-01
  • 2017-12-04
  • 2012-08-09
  • 2012-02-05
  • 2011-08-14
相关资源
最近更新 更多