douhuan1648 2015-02-25 19:49
浏览 49
已采纳

需要身份验证时,带有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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义