我正在尝试从跨域创建登录页面,但我无法解决问题,错误是:
XMLHttpRequest无法加载http://localhost/testing/resp.php。在预检响应中,Access-Control-Allow-Headers不允许使用请求标题字段Access-Control-Allow-Headers。
我的Javascript代码是:
$('#login').click(function(){
var username = $('#uname').val();
var password = $('#pass').val();
var result = $('.result');
result.text('loading....');
if (username != '' && password !=''){
var urltopass = 'action=login&username='+username+'&password='+password;
$.ajax({
type: 'POST',
data: urltopass,
headers: {"Access-Control-Allow-Headers": "Content-Type"},
url: 'http://localhost/testing/resp.php',
crossDomain: true,
cache: false,
success: function(responseText){
console.log(responseText);
if(responseText== "0"){
result.text('incorrect login information');
} else if (responseText == "1"){
window.location="http://localhost/testing/home.php";
} else{
alert('error in sql query \n' + responseText);
}
}
});
} else return false;
});

http://localhost/testing/resp.php的PHP代码:
<?php
include "db.php"; //Connecting to database
if (!isset($_SERVER['HTTP_ORIGIN'])) {
echo "This is not cross-domain request";
exit;
}
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header('P3P: CP="CAO PSA OUR"'); // Makes IE to support cookies
header("Content-Type: application/json; charset=utf-8");
if (isset($_POST['action']) && $_POST['action'] == 'login'){
$uname = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT * FROM loginajax WHERE username='$uname' AND password='$pass'";
$rs=$conn->query($sql);
if (mysqli_num_rows($rs) <= 0){
echo "0";
} else {
echo "1";
}
} else echo "this is not Login";
?>
&#13;
答案 0 :(得分:12)
删除它:
headers: {"Access-Control-Allow-Headers": "Content-Type"},
从你的jQuery.ajax调用。
服务器以Access-Control-Allow-Headers
标头响应,客户端不会将其发送到服务器。
客户端发送Access-Control-Request-Headers
请求允许某些标头,服务器以Access-Control-Allow-Headers
回复,列出其允许的实际标头。客户端无法要求允许哪些标头。