如何传递多个标题并覆盖内容类型?

时间:2014-08-20 15:12:58

标签: javascript arrays function

我有以下无法覆盖的功能:

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

如何将多个标题(aHeaders)传递给此函数?如果我将Content-Type作为标题传递,它会覆盖默认值(application/x-www-form-urlencoded)吗?

我想传递两个标题:

  1. x-myheader-valuezzz1111bbb
  2. content-typeapplication/javascript

1 个答案:

答案 0 :(得分:0)

似乎你的函数需要一个像这样的对象:

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

但是,如果您设置多次相同的标头,则预期的行为是该值将被连接,而不是替换...请参阅W3C specsMDN。因此,在您的情况下,如果在传递非空aPostData对象时传递Content-Type标头,则将以错误的标头值结束。