---
title: "ajax请求中设置特殊的RequestHeader"
author: "liyonghui160com"
date: "2016-12-12T10:40:15Z"
tags: []
categories: ["互联网"]
slug: "ajax-requestheader"
draft: false
lastmod: "2016-12-12T11:01:09Z"
id: 2344337
url: "https://liyonghui160com.iteye.com/blog/2344337"
---

**一.ajax请求，没有跨域，设置http header头部**

$.ajax({

    type: "post",

    url:"http://abc.cc/qrcode3/index.php/home/index/testpost",

    dataType: "json"

    data: {"key":"value"},

    // headers : {'Authorization':'Basic bmVvd2F5Oe4lb3dheQ=='},

    beforeSend: function(xhr) {

        xhr.setRequestHeader("Authorization", "Basic bmVvd2F5Oe4lb3dheQ==");

    },

    success: function(data){ alert(data); },

    error: function(data){ alert("error"); } ,

});

**设置header头部有两种方法：**  
**1.**headers : {‘Authorization’:’Basic bmVvd2F5Oe4lb3dheQ==’}

多个头部用逗号‘，’分隔开  
**2.**定义beforeSend方法  
beforeSend: function(xhr) {  
xhr.setRequestHeader(“Authorization”, “Basic bmVvd2F5Oe4lb3dheQ==”);  
}

**二.ajax跨域请求,没有设置http header,**

$.ajax({

    type: "post",

    url:"http://abc.cc/qrcode3/index.php/home/index/testpost",

    dataType: "jsonp"

    data: {"key":"value"},

    // headers : {'Authorization':'Basic bmVvd2F5Oe4lb3dheQ=='},

    success: function(data){ alert(data); },

    error: function(data){ alert("error"); } ,

});

服务器端代码：

public function testpost() {

    $data = $\_GET\['key']?$\_GET\['key']:"123456";

    $callback = $\_GET\['callback'];

    if(!preg\_match("/^\[0-9a-zA-Z\_.]+$/",$callback)){

exit('参数错误！');

    }

    echo $callback.'('.json\_encode($data).')';

    exit;

}

跨域ajax访问，使用jsonp，返回数据格式如：abc({'key':'value','key2':'value2'}),形如一个函数调用，参数为一个json数据格式

**三.ajax跨域请求，设置header头部的解决办法**

跨域无法直接设置header，如果跨域了还要设置http头，可以使用以下方法。

jquery实现代码如下：

$(".get\_data").click(function() {

    var key = $("#user").val() + ":" + $("#pass").val();

    //base64编码

    var authKey = base64encode(key);

    $.ajax({

        type: 'GET',

        dataType: 'json',

        url: "http://abc.cc/qrcode3/home/index/testajax",

        headers: {'Authorization': 'Basic '+authKey,"lpy":"lpy"},

        success: function(data) {

            alert(data.msg+"--"+data.user);

        },

        error:function(data){

            alert("error");

        }

    });

});

 

php实现代码如下：

public function testajax() {

    // 指定允许其他域名访问  

    header('Access-Control-Allow-Origin:http://abc.cn');  

    // 响应类型  

    header('Access-Control-Allow-Methods:POST,GET');  

    // 响应头设置，允许设置Authorization和lpy这两个http头

header('Access-Control-Allow-Headers:Authorization,lpy');

 

    //获取所有的http请求头

    $header = apache\_request\_headers();

$data\['lpy'] = $header\['lpy'];

//获取authorization中的用户名和密码，并判断

    $data\['user'] = $\_SERVER\['PHP\_AUTH\_USER'];

    $data\['pass'] = $\_SERVER\['PHP\_AUTH\_PW'];

    if($data\['user'] == "neoway" && $data\['pass'] == "neoway"){

        $data\['msg'] = "ok";

    }else{

        $data\['msg'] = "errorjsonp";

    }

echo json\_encode($data);

}

**总结：**  
ajax跨域是不能设置http header的，为了能够设置header，需要在服务器php代码中添加header(‘Access-Control-Allow-Origin:http://abc.cn’); 允许http://abc.cn访问服务器abc.cc，再通过设置header(‘Access-Control-Allow-Headers:Authorization,lpy’);把需要设置的http header属性添加进去，在jquery代码中通过header来设置响应的属性值，在http的请求头中就可以看到 Authorization和lpy的请求头，服务器php端通过$header = apache\_request\_headers()获取http header的数组，继而可以获取到lpy的请求头的值。