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

后端 未结 6 1451
小鲜肉
小鲜肉 2020-12-14 03:35

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 requ

6条回答
  •  生来不讨喜
    2020-12-14 03:53

    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.

提交回复
热议问题