0
var req = $.ajax({
            type: 'GET',
            cache: false,
            url: 'loc.aspx?count=' + str,
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            async: false,
            data:'{}',
            success: function (data) {
                alert(data.responseText);
            }
        });
        req.fail(function (data) {
        TINY.box.show({ html: 'Server Error. Try again: ' + data.responseText, animate: false, close: false, boxid: 'error', top: 100 });
        });

上面的代码曾经在 jsp 中正常工作,现在我正在尝试在 asp.net c# 中使用,无论如何我在错误块中获取正确的数据,我希望它在成功块中。甚至data.d没有帮助,

如果我写的东西就像alert(data)我得到了完整的 html,我只需要响应文本,当我这样使用data.responseText时,我会变得不确定。请有人帮忙。

谢谢

4

1 回答 1

0

下面的代码应该可以正常工作。我在你做错的地方添加了一些评论

var req = $.ajax({
            type: 'GET',
            cache: false,
            url: 'loc.aspx?count=' + str,
            dataType: 'html',// as you return a simple html dataType:json will throw an error as jquery will not be able to parse received string
            contentType: "application/json; charset=utf-8",
            async: false,
            data:'{}',
            success: function (data) {
                alert(data);// data is not an XHR object. it is a processed response. In your case - simple string with HTML which, of course, has no method responseText
            }
        });
        req.fail(function (data) {
        TINY.box.show({ html: 'Server Error. Try again: ' + data.responseText, animate: false, close: false, boxid: 'error', top: 100 });
        });

.fail函数中你有data.responseText因为在这种情况下 XHR 对象作为第一个参数传递(参见this)。同时successcallback的第一个参数是request接收到的干净数据。如果没有细节,你可以认为data == xhr.responseText在成功回调中。请参阅本节中的成功属性描述

更新

正如出现的那样,问题不仅在于 JS。我猜你有一个.aspx用 ajax 调用的简单页面。有两种解决方案:

1)改用网络服务。它会更好,因为它不会经历完整的页面加载周期并且应该更快地执行。它不会产生未使用的 HTML

2)aspx页面默认会输出一些HTML。在您返回 ajax 请求的响应之前,您应该清除响应(因此已经生成的 HTML 不会发送到服务器),写下您的响应并立即结束它:

Response.Clear();
Response.Write("hello");
Response.End();

这种方式你应该只收到hello成功。

于 2013-01-22T09:16:55.383 回答