jQuery $.ajax怎样发送header
使用headers:
headers:{
"token1": token1,
},
使用beforeSend:
beforeSend: function(request){
request.setRequestHeader("token2", token2);
},
示例:
<?php
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']=='XMLHttpRequest'){
var_dump($_SERVER);exit;
}
?>
<html>
<head>
<title>jQuery $.ajax send header</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
</head>
<body>
<form id="login-form">
<input type="text" placeholder="please input username" name="username"><br>
<input type="password" placeholder="please input password" name="password"><br>
<input type="button" name="submit" value="Submit">
</form>
<script>
$('#login-form input[name="submit"]').on('click', function (){
var username = $('#login-form input[name="username"]').val();
var password = $('#login-form input[name="password"]').val();
var token1 = 'aaaaaaaaaaaaaaa';
var token2 = 'bbbbbbbbbbbbbbb';
$.ajax({
headers:{
"token1": token1,
},
beforeSend: function(request){
request.setRequestHeader("token2", token2);
},
type:'post',
url:'',
data:{
username: username,
password: password,
},
success:function(response){
console.log(response)
}
});
});
</script>
</body>
</html>
新建一个php文件,复制以上代码到该文件中,浏览器访问该文件并打开浏览器控制台的『网络(Network)』,然后点击提交按钮,即可在控制台的Network中看到ajax请求,查看返回结果,可以看到有HTTP_TOKEN1和HTTP_TOKEN2,说明token1和token2header发送成功,只是它会自动给你转成大写,并且前面加上HTTP_
:
觉得文章对你有用的话鼓励一下我吧