-1

我正在尝试向外部 url 发出 AJAX 请求并尝试从该 url 获取 Json 数据。我收到 401-授权错误,表示尝试访问 url 时其内容不安全。下面是我的代码。请指教

function check() {

    var ENV_URL = 'http://../BlueLight/api/BlueLights/getActiveBlueLight';   
    $('#trBlueLight').hide();
    $.getJSON(ENV_URL+"&callback=?", function (data) {
        if (data.expDate != null) {
            $('#trBlueLight').show();
        } else {
            $('#trBlueLight').hide();
        }
    });
    }
4

2 回答 2

1

所以很想发表评论。我假设您创建以下文件proxy_loader.php并放入您的网络服务器目录(通常为 httpdocs)。它必须可以从https://domain.tdl/proxy_loader.php访问

该文件应如下所示:

<?PHP

// get the url provided by javascriot
$url= $_GET['url'];

// initialize CURL
$ch = curl_init();

// additional headers like session id etc.
$header = '';

// optional user & password
$userpass = 'user:password';

//$parameters for the request
// use parameter name as array key
// use parameter value as array value
$param = array();

// set url
curl_setopt($ch, CURLOPT_URL, $url);
//this enables the output into a variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// set optional header
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// set request method to GET
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
// optional http authenfication
// remove the // to enable
// curl_setopt($ch, CURLOPT_USERPWD, $userpass);
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);

// execute the request
// and save the response in $ret
$ret = curl_exec($ch);

// close the connection
curl_close($ch);

echo $ret;

// maybe you must use this:
// echo json_encode($ret);
?>

现在您可以使用如下函数通过您的服务器请求一个 url:

function check() {

    var ENV_URL = 'http://../BlueLight/api/BlueLights/getActiveBlueLight';   

    $('#trBlueLight').hide();

    $.getJSON('/proxy_loader.php?url=' + ENV_URL, function (data) {
        if (data.expDate != null) {
            $('#trBlueLight').show();
        } else {
            $('#trBlueLight').hide();
        }
    });
}
于 2013-05-03T07:50:50.103 回答
0

如果您可以在两个域上放置代码,XDM 很容易获得,代码示例在这里

于 2013-05-03T10:21:06.543 回答