安全 Javascript GET 请求

Secure Javascript GET Request

本质上,我有一个自定义 HTML 图表,需要来自外部安全代理服务器的值。现在,我将 HTML 块插入到页面上包含 JavaScript 的相关区域,以通过 XHTTP GET 请求获取正确的数据。

在我们将对代理服务器的访问限制为从我们的 C5 站点限制为我们的 SSL(这也是我们想要的)之前,它工作得很好。

这会阻止图表获得正确的值,因为 HTML 和 JavaScript 是在客户端而不是通过 C5 执行的。

本质上,我需要做的(我认为)是将 GET 请求移到 C5 中,以便它可以通过 SSL 证书。然后我需要获取该值并将其重新插入图表中。

下面是一些伪代码,这些伪代码基于我当前放入页面的 HTML 代码。

<!-- This is the actual HTML block that I'm creating. -->
<div id="HTMLBlock455" class="HTMLBlock">
<div class="someCustomChart">

<!-- Here's the script currently running that gets the necessary data and calls the proper functions to populate the chart.  -->

<script type="text/javascript">

// Global Var to store updating value 
var amount = 0;

// Open a new HTTP Request)
var xhr = new XMLHttpRequest();
xhr.open("GET", "Some_ElasticSearch Server", true);
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      var person = JSON.parse(xhr.responseText);
      amount = person._source.age; // Grabs the person age
      $('#chart_328').data('updateto', amount); //updates the above HTML data    value
            document.getElementById('chart_328_text').innerHTML = amount + '%';
    } else {
      console.error(xhr.statusText);
   }
  }
};
xhr.onerror = function (e) {
 console.error(xhr.statusText);
};
xhr.send(null);

// This function executes on page load and prepares the chart!
$(document).ready(function() {
   ....
}

您可以向另一个域或协议发出 Ajax 请求,只需在您想要访问的后端启用 CORS

另一个选项,但我不知道这在 C5 中是否可用,是创建代理传递请求。在这种情况下,C5 将作为您请求的代理。那么流程是:

Ajax request to your C5 -> C5 proxies the request to the external resource -> C5 sends you back the result

我更喜欢 CORS 的方法,但考虑到旧版浏览器无法 100% 兼容。见参考:http://caniuse.com/#feat=cors