jQuery AJAX 设置header 跨域 || 不跨域

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


$.ajax({
            type: "post",
            url:"http://xxx",
            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");        
                }    
            });
        });

在这里插入图片描述

转载自:https://www.jianshu.com/p/34af1f99f9d9

更多jQuery ajax 配置可以参考手册: http://www.w3school.com.cn/jquery/ajax_ajax.asp

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值