[PHP] 纯文本查看 复制代码 <?php
$_header = 'X-Requested-With,X_Requested_With,sign,token,version,source,Content-Type,Content_Type,Referer,User_Agent,User-Agent,Origin';
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods:POST,GET,OPTIONS');
header("Access-Control-Allow-Headers:$_header");
echo 2;
?>
这是php文件
[HTML] 纯文本查看 复制代码 <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
aj();
//get();
//post();
function aj(){
var url = 'http://192.168.0.111:81/a';
var data = {'name': 'John', 'age': 30};
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
success: function(response) {
console.log(response);
}
});
}
function get(){
let xhr = new XMLHttpRequest();
xhr.open('GET', 'http://192.168.0.111:81/a');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
}
function post(){
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://192.168.0.111:81/a', true);
xhr.setRequestHeader('Content-type', 'application/json');
//xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('Error');
}
};
var data = {name: 'John', age: 30};
var jsonData = JSON.stringify(data);
var ss="name=123&pass=456";
xhr.send(jsonData);
}
</script>
这是html代码
当发起get与post的正常请求时没问题
但是post数据为json时就会提示cors错误大意是不允许跨域请求这种情况要怎么处理呀
@大司命
|