2012-09-21 19 views
11

Ho una chiamata ajax in cui ho utilizzato jQuery.ajax() per effettuare una richiesta a un'azione mvc. Tutto ha funzionato bene. Tuttavia, a causa di alcuni moduli con un controllo file, l'ho modificato dall'utilizzo di jQuery.ajax() all'utilizzo di XMLHttpRequest per inviarlo utilizzando l'API file HTML5.XMLHttpRequest non aggiunge intestazione - "X-Requested-With: XMLHttpRequest"

Dopo aver apportato questa modifica, il metodo di azione MVC non lo vede più come una richiesta Ajax. Usando Fiddler2 ho notato che non aggiunge più alla richiesta "X-Requested-With: XMLHttpRequest" e presumo che questo sia il problema.

Il modulo che sto tentando di inviare non ha un input di file, solo normali caselle di testo ecc., Ma stavo cercando di mantenere il metodo generico per gestire entrambi. Quello che segue è il codice che sto usando per inviare la richiesta ajax:

// get the edit tender form 
var $Form = $Button.closest('form'); 
var Url = $Form.attr('action'); 
var AjaxRequestObject = new XMLHttpRequest(); 
var FormDataToSend = new FormData(); 

$Form.find(':input').each(function() { 
    if ($(this).is('input[type="file"]')) { 
     var files = $(this)[0].files; 
     if (files.length > 0) { 
      FormDataToSend.append(this.name, files[0]); 
     } 
    } else { 
     FormDataToSend.append(this.name, $(this).val()); 
    } 
}); 

AjaxRequestObject.open('POST', Url, true); 
AjaxRequestObject.onreadystatechange = function() { 
    if (AjaxRequestObject.readyState == 4) { 
     // handle response. 
     if (AjaxRequestObject.status == 200) { 
      if (!AjaxErrorExists(AjaxRequestObject.responseText,)) { 
       alert("success"); 
       console.log(AjaxRequestObject.responseText); 
      } 
      else { 
       alert('failure'); 
      } 
     } 
     else { 
      alert('failure'); 
     } 
    } 
}; 

AjaxRequestObject.send(FormDataToSend); 

Questo codice è stato fornito a seguito di un problema che ho avuto che Darin Dimitrov ha fornito la soluzione per, così ho potuto inviare gli ingressi di file da ajax.

Qualche idea sul perché questa richiesta non invia l'intestazione per una chiamata Ajax?

risposta

13

X-Requested-With viene aggiunto automaticamente da jQuery. Puoi facilmente aggiungerlo tu stesso con AjaxRequestObject.setRequestHeader(). Docs

+2

Super non lo sapevo. Direttamente prima dell'invio, ho aggiunto quanto segue: "AjaxRequestObject.setRequestHeader ('X-Requested-With', 'XMLHttpRequest');" e penso che abbia funzionato – eyeballpaul

4

Avevo difficoltà a rilevare se la mia richiesta era ajax. Quindi, forse questo campione salvare qualcuno un paio di minuti:

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(); 

Testato con Flask.

0

È possibile ignorare nativamente tutte le chiamate di metodo XMLHttpRequest.open e aggiungere in esso X-Data-Con intestazione come:

(function() { 

    // @author https://github.com/stopsopa jfdsa78y453cq5hjfd7s877834h4h3 

    if (window.XMLHttpRequest.prototype.onOpen) { 
     return console.log('XMLHttpRequest.onOpen is already defined'); 
    } 

    function over(method, on, off) { 

     var old = window.XMLHttpRequest.prototype[method]; 

     if (!old.old) { 

      var stack = []; 

      window.XMLHttpRequest.prototype[on] = function (fn) { 
       if (typeof fn === 'function') { 
        stack.push(fn); 
       } 
      } 

      window.XMLHttpRequest.prototype[off] = function (fn) { 
       for (var i = 0, l = stack.length ; i < l ; i += 1) { 
        if (stack[i] === fn) { 
         stack.splice(i, 1); 
         break; 
        } 
       } 
      } 

      window.XMLHttpRequest.prototype[method] = function() { 
       var args = Array.prototype.slice.call(arguments); 

       var ret = old.apply(this, args); 

       for (var i = 0, l = stack.length ; i < l ; i += 1) { 
        stack[i].apply(this, args); 
       } 

       return ret; 
      } 

      window.XMLHttpRequest.prototype[method].old = old; 
     } 
    } 

    over('open', 'onOpen', 'offOpen') 

    XMLHttpRequest.prototype.onOpen(function() { 
     this.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); 
    }); 
}());