0

I'm just looking at some Ajax requests in Fiddler whilst testing some exception handling classes and code in my application and I'm not sure my requests are well formed and as they should be.

My Javascript is:

$(function () {
    $('#createentry').submit(function () {
        e.preventDefault();
        $.ajax({
            url: this.action,
            type: this.method,
            dataType: "json",
            data: $(this).serialize(),
            success: function(result) {
                $('#entries-list').append("<li>" + $('#newentry').val() + "</li>");
                $('#newentry').val('').blur();
            },
            error: function (xhr)
            {
                try
                {
                    var json = $.parseJSON(xhr.responseText);
                    alert(json.errorMessage);
                }
                catch (e)
                {
                    alert('something bad happened');
                }
            }
        });
        return false;
    });
});

In Fiddler the request looks like:

Host: localhost:54275
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost:54275/Diary
Cookie: __RequestVerificationToken= <snipped for brevity>
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 216

I would expect the Accept: header to be set to json automatically I guess that's an incorrect assumption on my part, how is this set?

Also if I looks at the result of this in my action method the value is always false:

    [HttpPost, ValidateAntiForgeryToken, JsonExceptionFilter]
    public JsonResult PostNewEntry(DiaryEntryViewModel diaryEntry)
    {
        var req = Request.IsAjaxRequest();

req always = false so my JsonExceptionFilter isn't kicking in and taking care of the error reporting as expected.

Is there also a defined way of forcing only accepting requests correctly setup as Ajax requests in MVC?

4

2 回答 2

3

我发现这个超过五年的错误说使用.ajax()脚本dataType或 JSON 会导致缺少标头是一项功能。但我想Request.IsAjaxRequest()正在寻找那个确切的标题。

作为一种解决方法,您可以尝试执行以下操作:

$(document).ajaxSend(function (event, request, settings) {
    request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
});

它将将该标头附加到 jQuery 发送的每个 Ajax 调用中。

于 2013-04-28T20:48:10.967 回答
0

在尝试了几乎所有我在网上可以找到的解决方案但绝对没有成功之后,我选择开始使用jQuery 表单插件,现在我在服务器端收到了格式良好的 Ajax 请求。

从上面的链接下载插件,然后我将我的 Ajax JavaScript 替换为:

$(document).ready(function () {
    $('#createentry').ajaxForm(function () {
        alert("Thank you for your comment!");
    });
});

包含此脚本并测试对以下内容的调用后:

Request.IsAjaxRequest();

现在正确返回 true。

使用Firebug检查被发布的请求所需的标头,该标头将请求表示为 Ajax 请求存在:

X-Requested-With XMLHttpRequest
于 2013-04-29T19:19:51.540 回答