开发者

Jquery, No X-Requested-With=XMLHttpRequest in ajax request header?

开发者 https://www.devze.com 2022-12-13 15:29 出处:网络
SOME TIMES there is no X-Requested-With header, sometimes there is. I checked in firebug and found that, don\'t know why.

SOME TIMES there is no X-Requested-With header, sometimes there is.

I checked in firebug and found that, don't know why.

So when I use request.is_ajax in django, it fails sometimes.

Anyone know how to fix it?


OK, now it happened again. I opened the page and then left for supper for a long while, when I came back, it happened again. I recorded request header in firbugs:

Request with X-Requested-with:

Host localhost:8000

User-Agent Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.5) Gecko/20091102

Firefox/3.5.5

Accept text/html, /

Accept-Language zh-cn,zh;q=0.5

Accept-Encoding gzip,deflate

Accept-Charset GB2312,utf-8;q=0.7,*;q=0.7

Keep-Alive 300

Connection 开发者_StackOverflow中文版keep-alive

X-Requested-With XMLHttpRequest

Referer http://localhost:8000/gallery/

Cookie xxx

Request without X-Requested-with:

Host localhost:8000

User-Agent Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.5) Gecko/20091102

Firefox/3.5.5 Accept text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8 Accept-Language zh-cn,zh;q=0.5 Accept-Encoding gzip,deflate

Accept-Charset GB2312,utf-8;q=0.7,*;q=0.7

Keep-Alive 300

Connection keep-alive

Referer http://localhost:8000/gallery/

Cookie xxx


Provide more information. What kind of ajax requests are you making?

If you are submitting forms which contain an input field of type file that is most likely the reason that the header is missing.

As you can't submit a file with ajax, all the javascript frameworks use the "hidden iframe" trick internally to get the work done for you.

Check this post with a similar problem and my answer to it.

X-Requested-With header not set in jquery ajaxForm plugin


Otherwise there should be no reason for such a behavior from jQuery as it always sets the header. If the issue isn't related to file-inputs please post relevant codesnippets

from jQuery Source

xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");


I was facing this issue as well with version 1.6.2, especially when the page has been setting idle for a while. Expanding on jitter's answer, this is adding the X-Requested-With redundantly for every request in one place. I put this in my Master page. Hope this works out.

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


I was just having the same problem myself, and I fixed it by ensuring there was a trailing slash after my url. So instead of:

$.get('/example/url')

use:

$.get('example/url/')

Looks like it's been a while since you posted this but maybe it will help!


The reason I got this was because I was taking an element with my AJAX event handler attached, cloning it and then adding the new element to my document. For some reason this meant that the event attached to the new element would not treat it as a normal ajax request (Accept:text/html instead of application/json, no X-Requested-With etc.)

To fix this all I did was change the event to jQuery's new equivalent of live() (unsure what they call it now). So from:

$('a.basket-add').click(function() { /* etc */ });

To:

$(document).on('click', '.basket-add', function() { /* etc */ });


this may not be THE answer, but I was clawing my eyeballs out for a couple hours before figuring out that my mistake was pretty bone-headed. (What was killing me is that it was working on my dev box but not in production, and I still don't get why that is so, but...)

Make sure the event handler is really attached! If there's no X-Requested-With header it may be for good reason! I had a form whose action attribute was the correct url, and my submit button's "click" event was saying event.preventDefault() and then calling $.post(...), yadda yadda. Problem is, that DOM element was getting replaced as the result of some other xhr activity, and its event handler was getting blown away with it. The form was being submitted as a plain old POST, not ajax, hence no header.

So, rather than

$('#my-submit-button').on("click", data, function(event) {
    event.preventDefault();
    $.post(/* etc */);
})

it needed to be something like

$('#parent-div').on("click","#my-submit-button", function(event){
    event.preventDefault();
    $.post(/* etc */);
});

Further reading: https://learn.jquery.com/events/event-delegation/


Try this also by including the X-Requested-With as part of the Post values.

var postData = "X-Requested-With=XMLHttpRequest&" + $("#myFormId").serialize();
$.post(
    'http://www.mysite.com/blahblah',
    postData,
    function(data) { /*do whatever*/ },
    'html'
);

That and combine it with jitter's answer. Hope it helps!

EDIT NOTES:

I apologize I don't know what I was thinking. I must have misread the question when I posted.
This question is for Python django framework. Not for ASP.NET MVC.

I posted this answer because of the ASP.NET MVC's behavior based on the following source code.

ASP.NET MVC Source Code

Look at the AjaxRequestExtensions.cs class in the ASP.NET MVC source. http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/60c2f18ed84838b1b3da671536a7a40033e67b0d#src/System.Web.Mvc/AjaxRequestExtensions.cs.

public static class AjaxRequestExtensions
{
  public static bool IsAjaxRequest(this HttpRequestBase request)
  {
      if (request == null)
      {
          throw new ArgumentNullException("request");
      }

      return (request["X-Requested-With"] == "XMLHttpRequest") ||
             ((request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest"));
  }
}

MSDN Documentation on HttpRequestBase.Item Property

HttpRequestBase.Item Property
When overridden in a derived class, gets the specified object from the Cookies, Form, QueryString, or ServerVariables collections.

Therefore, request["X-Requested-With"] will look for that key in all the following places:

  • HTTP Form POST values
  • HTTP Cookie
  • HTTP Request Query String
  • and Server Variables.

So, if you include the X-Requested-With=XMLHttpRequest key-value pair as part of the HTTP POST like I am doing in the jQuery AJAX call, ASP.NET MVC will consider the HTTP Request as an AJAX HTTP Request.

0

精彩评论

暂无评论...
验证码 换一张
取 消