js的ajax请求相关
1.检查请求是否是ajax请求
if(isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest"){
echo 'ajax请求';
}
2.php服务器允许域名进行跨域请求:
<?php
//允许跨域请求 , 是HTML5提供的方法,对跨域访问提供了很好的支持
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
header("Access-Control-Allow-Origin:".$origin); //允许域名,当跨域需要发送cookie时,$origin必须为跨域的域名
header("Access-Control-Allow-Methods:POST,GET,OPTIONS");//允许请求的类型
header("Access-Control-Allow-Headers: Origin,X-Requested-With,Content-Type,Accept");//请求的头信息
header("Access-Control-Allow-Credentials:true"); //请求是否允许发送cookie
3.js跨域并发送cookie信息
$(function(){
$.ajax({
type:'post',
url:'http://localhost/test/1/return_ajax.php',
dataType:'json',
xhrFields: {
withCredentials: true //此处为true时系统会带上cookie发送请求
},
async:false, //同步 true为异步
crossDomain: true, //跨域代理可以保证验证码和请求的接口使用的是同一个session
success:function(e){
console.log(e);
}
});
});
4.js原生ajax请求
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","a.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<h3>请在下面的输入框中键入字母(A - Z):</h3>
<form action="">
姓氏:<input type="text" id="txt1" oninput="showHint(this.value)" />
</form>
<p>建议:<span id="txtHint"></span></p>
</body>
</html>
浙公网安备 33010602011771号