douhuan1648
2015-02-25 19:49
浏览 46

需要身份验证时,带有JSON的跨源AJAX请求中断

I am trying to make an AJAX call to a PHP file on a different site:

$.ajax({                                      
    type: "GET",
    dataType: "json",
    url: 'http://user:password@www.myurl.com/myphpfile.php',
    data: {
        records: JSON.stringify(workingarray),
        account: account,
    },

    complete: function(response) {
        var parsedresponse = $.parseJSON(JSON.stringify(response)).responseText.split("<br>");
        otherFunction(parsedresponse);
    }
});

My PHP file:

<?php
header('Access-Control-Allow-Origin: *');
header('content-type: application/json; charset=utf-8');

$records = json_decode($_GET['records']);
$account = $_GET['account'];

 .....[LOGIN AND SQL QUERY].....

$result = $conn->query($sql);

while ($row = $result->fetch_assoc()) {
    echo json_encode($row['Some columns']."<br>", JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }

$conn->close();
?>

This all worked great until I noticed I hadn't actually turned on authentication. Once I did that, the whole thing just broke down, and I always get the following error:

XMLHttpRequest cannot load http://user:password@www.myurl.com/myphpfile.php (...) . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://originurl.co.uk' is therefore not allowed access. The response had HTTP status code 401.

As you will see from my PHP code however, there IS a header present. I have also tried adding the following 2 lines to my .htaccess:

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Credentials true

With frustratingly little effect, which is to say, no effect whatsoever.

I have attempted to convert the datatype to JSONP, but I am not really sure how to go about doing this... I have tried the following changes:

$.ajax({                                      
    type: "GET",
    dataType: "jsonp",
    url: 'http://user:password@www.myurl.com/myphpfile.php?callback=?',
    data: {
        records: JSON.stringify(workingarray),
        account: account,
    },

    complete: function(response) {
        var parsedresponse = $.parseJSON(JSON.stringify(response)).responseText.split("<br>");
        otherFunction(parsedresponse);
    }
});

My PHP file:

<?php
header('Access-Control-Allow-Origin: *');
header('content-type: application/jsonp; charset=utf-8');

...

while ($row = $result->fetch_assoc()) {
    echo $_GET['callback'] . "(" . json_encode($row['Some columns']."<br>", JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . ")";
    }

$conn->close();
?>

This doesn't result in an error in the console as far as I can see, but the only thing I could make sense of in the response was this:

status: 200

statusText: "load"

(I added a console.log(parsedresponse) line to the complete: function for debugging purposes, but I must admit I am not entirely sure how to interpret most of what I am seeing.)

Any help or suggestions would be much appreciated because this is causing me a lot of frustration.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dougu1985 2015-02-27 12:56
    已采纳

    I believe I have solved the problem - I have not quite fully rewritten the application but I am able to make the call and get a response so it should all be plain sailing from here on out (famous last words, haha).

    Anyway, the changes I made were as follows - I firstly switched complete for success in the AJAX call:

    $.ajax({                                      
        type: "GET",
        dataType: "jsonp",
        url: 'https://user:password@www.myurl.com/myphpfile.php?callback=?',
        data: {
            records: JSON.stringify(workingarray),
            account: account,
        },
        success: function(response) {
            console.log(response);
            otherFunction(response);
        }
    });
    

    And then, and I think this was probably the main issue, I had to rewrite this part of the PHP file...

    $result = $conn->query($sql);
    
    while ($row = $result->fetch_assoc()) {
        echo json_encode($row['Some columns']."<br>", JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        }
    

    ...to become:

    $result = $conn->query($sql);
    $rows = array();
    
    while ($row = $result->fetch_assoc()) {
            $rows[] = array('data' => $row['Some columns']);
        }
    
    echo $_GET['callback'] . "(" . json_encode($rows, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . ")";
    

    ...as obviously (in retrospect) my previous method was returning multiple functions with the same name.

    I have also changed the request URL to https, which should be secure enough for the intended use, I think.

    Anyway hope someone finds my experience useful.

    点赞 打赏 评论

相关推荐 更多相似问题