【问题标题】:ASP.Net jQuery AJAX call not workingASP.Net jQuery AJAX 调用不起作用
【发布时间】:2015-09-05 15:22:48
【问题描述】:

我正在尝试为此按钮的点击事件调用代码隐藏方法:

<input type="button" id="btn_submit1" class="btn btn-default" value="Calculate" />

这里是它的 AJAX 调用:

$(document).ready(function() {

    $("#btn_submit1").click(function() {

        var msg = $("#txt_1_1").val();

        $.ajax({
            type: 'POST',
            url: 'Calc.aspx/calculate',
            data: '{sText:' + msg + '}',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(response) {
                alert("success!!");
                alert(response.d);
                $("#test").html(response.d);
            },
            failure: function(response) {
                alert(response.d);
            }
        });
    });

});

这是 WebMethod:

[System.Web.Services.WebMethod]
    public static string calculate(string sText)
    {
        System.Diagnostics.Debug.WriteLine("sText = " + sText);
        return sText;
    }

成功部分的两个警报都被调用,但第二个警报显示“未定义”,因此 div“测试”中没有显示任何内容。 我搜索了很多,但找不到代码有什么问题。

此外,Debug.WriteLine 不会在“输出”窗口中打印任何内容。在网上搜索后使用了这个,我不确定它是否是正确的打印方式。

【问题讨论】:

  • 大概然后response.d 是未定义的。 response 中有什么内容?为什么你期望它有一个d 属性?
  • "Debug.WriteLine does not print anything in the Output window" - 什么输出窗口?这是一个 Web 应用程序,它们通常没有与之关联的控制台窗口。
  • @Archer - console.log(data) 在 Chrome 控制台中显示此错误 - Uncaught ReferenceError: data is not defined 但是 console.log(msg) 显示我在文本框“txt_1_1”中的所有内容。
  • 对不起 - 我的错(习惯的力量)。将其更改为 console.log(response); 它会准确显示返回的内容,而不是 [object Object]
  • @Archer - 这是 console.log(response) 控制台中的消息: Object {Message: "Authentication failed.", StackTrace: null, ExceptionType: "System.InvalidOperationException"}

标签: javascript jquery asp.net ajax web-services


【解决方案1】:

响应的“.d”部分是 Microsoft 添加到 ASP.NET 3.5 以封装 JSON 对象的安全功能。您可以通过以下方式检查是否需要使用“.d”:

if (response.hasOwnProperty("d")) {
    console.log(response.d);
    var myData = $.parseJSON(response.d);
} else {
    console.log(response);
}

编辑:在这种情况下,您可能不需要使用“.d”,因为您返回的数据不是有效的 JSON,很可能是字符串。

编辑 2:从您在评论中提到的内部服务器错误看来,您的数据格式可能不正确。我只是在这里猜测,但你可以试试:

var datapackage = {
    msg: $("#txt_1_1").val()
};
var datapacked = JSON.stringify(datapackage);

然后在AJAX调用上放“data:datapacked”。

【讨论】:

  • 对象 {消息:“身份验证失败。”,StackTrace:空,异常类型:“System.InvalidOperationException”}
  • 那么恐怕问题出在您的 ASP WebMethod 上。你可以在这里查看这个问题的答案:stackoverflow.com/questions/23033614/…
  • 没有帮助。得到这个错误: POST localhost:44300/Calc.aspx/calculate 500 (Internal Server Error) send @ jquery-1.10.2.js:8720 jQuery.extend.ajax @ jquery-1.10.2.js:8150 (匿名函数) @Calc.aspx:114 jQuery.event.dispatch @jquery-1.10.2.js:5109 elemData.handle @jquery-1.10.2.js:4780
  • 我已经用你可以尝试的东西再次编辑了我的答案......这可能是错误是由于传入的 JSON 不正确造成的。
  • 不。还是同样的错误。这让我现在疯了:@
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多