一.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