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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题