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

后端 未结 6 1455
小鲜肉
小鲜肉 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 04:03

    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/

提交回复
热议问题