0

I have the following function which I can not override:

  getHtml:function(aURL,aPostData,aHeaders,aMethod){
    this.xhr = new XMLHttpRequest();
    var tmp=this;
    this.xhr.onreadystatechange=function(){
      tmp.onStateChange();
    };
    if(aPostData||aPostData==""){
      this.xhr.open(aMethod?aMethod:"POST", aURL, true);
      this.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    }else this.xhr.open(aMethod?aMethod:"GET", aURL, true);
    if(aHeaders){
      for(var t in aHeaders){
        this.xhr.setRequestHeader(t,aHeaders[t]);
      }
    }
    try{
      this.xhr.send(aPostData);
    }catch(e){
      this.doNext("");
    }
  }

How should I pass several headers (aHeaders) to this function? If I pass Content-Type as the header, will it override default value (application/x-www-form-urlencoded) there?

I would like to pass two headers:

  1. x-myheader-value: zzz1111bbb
  2. content-type: application/javascript
LA_
  • 19,823
  • 58
  • 172
  • 308
  • What circumstances to you have where it makes sense to POST JavaScript to the server and get HTML back? – Quentin Aug 20 '14 at 15:16

1 Answers1

0

It seems your function expects an object like:

var headers = {
    "x-myheader-value": "zzz1111bbb", 
    "Content-Type": "application/javascript"
};
...
getHtml( ... , headers, ...);

However if you set multiple times the same header, the expected behaviour is that the value would be concatenated, not replaced... See W3C specs or MDN. So in your case, if you pass the Content-Type header when also passing a non empty aPostData object, you will end with the wrong header value.

Daniel J.G.
  • 34,266
  • 9
  • 112
  • 112
  • By the way, header names are [case insensitive](http://stackoverflow.com/questions/5258977/are-http-headers-case-sensitive) – Daniel J.G. Aug 20 '14 at 16:04
  • Thanks, Daniel. Is there any trick I can use to override (=replace) the content type value, when that `getHtml` function is used? As you mentioned, it concatenates the value, which is wrong. Let's say, can I somehow pass payload data in the header instead of usage `aPostData`? – LA_ Aug 27 '14 at 10:36
  • The cleanest way would be for that function not to add a content-type header if there is one in the argument aHeader. But you mentioned that you cannot change that function... – Daniel J.G. Aug 27 '14 at 11:42