XMLHttpRequest not adding header - “X-Requested-With: XMLHttpRequest”

前端 未结 3 2049
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 02:41

I have an ajax call where I used jQuery.ajax() to make a request to an mvc action. This all worked fine. However due to some forms having a file control I changed it from us

3条回答
  •  一向
    一向 (楼主)
    2020-12-30 03:34

    I was having troubles with detecting if my request was ajax. So, maybe this sample will save someone a minute or two:

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open('GET', URL, true);  // `true` for async call, `false` for sync.
    
    // The header must be after `.open()`, but before `.send()`
    xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    
    xmlhttp.onreadystatechange = function() {
        // 4th state is the last:
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { ... }
    };
    xmlhttp.send();
    

    Tested with Flask.

提交回复
热议问题