2016-02-05 19:36
浏览 827


I am trying to make a login page from cross domain but I couldn't solve the problem, the error is:

XMLHttpRequest cannot load http://localhost/testing/resp.php. Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers in preflight response.

My Javascript code is:

        var username = $('#uname').val();
        var password = $('#pass').val();
        var result = $('.result');

        if (username != '' && password !=''){
            var urltopass = 'action=login&username='+username+'&password='+password;
                type: 'POST',
                data: urltopass,
                headers: {"Access-Control-Allow-Headers": "Content-Type"},
                url: 'http://localhost/testing/resp.php',
                crossDomain: true,
                cache: false,
                success: function(responseText){
                    if(responseText== "0"){
                        result.text('incorrect login information');
                    } else if (responseText == "1"){
                    } else{
                        alert('error in sql query 
' + responseText);
        } else return false;

The PHP code for http://localhost/testing/resp.php :

    include "db.php"; //Connecting to database

    if (!isset($_SERVER['HTTP_ORIGIN'])) {
        echo "This is not cross-domain request";
    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'";

        if (mysqli_num_rows($rs) <= 0){
            echo "0";
        } else {
            echo "1";
    } else echo "this is not Login";


  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douci4026 2016-02-05 19:54

    remove this:

    headers: {"Access-Control-Allow-Headers": "Content-Type"},

    from your jQuery.ajax call.

    The server responds with a Access-Control-Allow-Headers header, the client doesn't send it to the server.

    The client sends a Access-Control-Request-Headers to request allowing certain headers, the server responds back with with a Access-Control-Allow-Headers that lists the actual headers its going to allow. The client does not get to demand what headers are allowed.

    解决 无用
    打赏 举报

相关推荐 更多相似问题