Set special RequestHeader in ajax request

 

 

1. Ajax request, no cross-domain, set http header 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"); } ,

});

There are two ways to set the header header
: 1. headers : {'Authorization':'Basic bmVvd2F5Oe4lb3dheQ=='}

Multiple headers are separated by commas ','
2. Define the beforeSend method
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic bmVvd2F5Oe4lb3dheQ==");
}


2. Ajax cross-domain request , no http header is set ,

$.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"); } ,

});

Server side code:

public function testpost() {

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

    $callback = $_GET['callback'];

    if(!preg_match("/^[0-9a-zA-Z_.]+$/",$callback)){

exit('Parameter error!');

    }

    echo $callback.'('.json_encode($data).')';

    exit;

}

Cross-domain ajax access, using jsonp, the returned data format is: abc({'key':'value','key2':'value2'}), which is like a function call, and the parameter is a json data format

Three . Ajax cross-domain request, the solution of setting the header header

The header cannot be set directly across domains. If you need to set the http header across domains, you can use the following methods.

The jquery implementation code is as follows:

$(".get_data").click(function() {

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

    //base64 encoding

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

        }

    });

});

 

The php implementation code is as follows:

public function testajax() {

    // Specify to allow other domain names to access  

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

    // response type  

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

    // Response header settings, allowing to set the two http headers Authorization and lpy

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

 

    //Get all http request headers

    $header = apache_request_headers();

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

/ / Get the user name and password in the authorization, and judge

    $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的请求头中就可以看到 Authorizationlpy的请求头,服务器php端通过$header = apache_request_headers()获取http header的数组,继而可以获取到lpy的请求头的值。

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326836074&siteId=291194637