位置ajax XMLHttprequest中的标头?

时间:2011-05-04 06:41:38

标签: ajax post xmlhttprequest

我必须在POST方法中将标题放在ajax和XMHttp请求中,如

例如: headers.put("X-PAYPAL-SECURITY-USERID", "tok261_biz_api.abc.com"); headers.put("X-PAYPAL-SECURITY-PASSWORD","1244612379");

的Ajax:

$.ajax({
    type:'POST',
    url:'url',
    data: dataobject,
    cache:false,
    dataType:'json',
    success:onSuccess,
    error:function(xhr,ajaxOptions){
        alert(xhr.status + " :: "  + xhr.statusText);
                    }
       });

的XMLHTTP:

var http = new XMLHttpRequest();
http.open("POST", url, true);

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
    alert(http.responseText);
}

1 个答案:

答案 0 :(得分:2)

如果这是jQuery 1.5,您可以使用headers属性:

$.ajax({
    type:'POST',
    url:'url',
    headers: {
        "X-PAYPAL-SECURITY-USERID": "tok261_biz_api.abc.com",
        "X-PAYPAL-SECURITY-PASSWORD": "1244612379"
    },
    data: dataobject,
    cache:false,
    dataType:'json',
    success:onSuccess,
    error: function(xhr,ajaxOptions) {
        alert(xhr.status + " :: "  + xhr.statusText);
    }
});

在以前的版本中,您可以使用beforeSend方法:

$.ajax({
    type:'POST',
    url:'url',
    beforeSend: function(xhr) { 
        xhr.setRequestHeader('X-PAYPAL-SECURITY-USERID', 'tok261_biz_api.abc.com'); 
        xhr.setRequestHeader('X-PAYPAL-SECURITY-PASSWORD', '1244612379'); 
    }, 
    data: dataobject,
    cache:false,
    dataType:'json',
    success:onSuccess,
    error: function(xhr,ajaxOptions) {
        alert(xhr.status + " :: "  + xhr.statusText);
    }
});