【问题标题】:cross domain request data using pure javascript使用纯javascript跨域请求数据
【发布时间】:2016-05-04 19:24:54
【问题描述】:

我正在尝试访问一个返回 json 数据的外部 url,并且基于该数据中的一个值,我需要隐藏一个表行。我已经尝试了几个选项来使用 jsonp、jquery 和 ajax 来做到这一点,但似乎没有任何效果。 YQL 为我工作,但我不能使用外部服务,因为代码需要独立。请有人告诉我如何使用 javascript 进行这项工作

这是我尝试过的一种方法

<script type='text/javascript'>



    function checkBlueLight() {

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

        $.getJSON('http://.../Lights/getBlueLight?callback=?', function (data) {
            if (data.expDate != null) {
                $('#trBlueLight').show();
            } else {
                $('#trBlueLight').hide();
            }
        });
        }



    </script>

这是我尝试过的另一种方法。同样的问题未经授权 - 401

$.ajax({
    url: 'http://.../Lights/getBlueLight',
    dataType: 'json',
    success: function(data) {
       if (data.expDate != null) {
           $('#trBlueLight').show();
       } else {
           $('#trBlueLight').hide();
       }
    }
});  

我什至尝试使用 jsp 从 url 获取数据,这也导致了一些权限问题

【问题讨论】:

  • 到目前为止你尝试过的代码是什么?
  • 我已经尝试过 jquery-JSONP 与回调和 Ajax-Json 组合的组合
  • 你能把你的代码贴在这里吗?
  • 我将它添加到我的问题中。请看

标签: javascript cross-domain


【解决方案1】:

你控制外部网址吗?因为你可以这样做:

在您的本地页面上:

function your_function(data) {
        alert(data.message)
}

然后在 http://www.include.me/remote.php(或任何返回 JSON 的)上,你会让它返回

your_function({message: "it works!"});

然后返回您的本地页面:

var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "http://www.include.me/remote.php");
document.getElementsByTagName("head")[0].appendChild(script);

然后将包含脚本,它只是告诉它使用它提供的数据运行您已经定义的函数。

【讨论】:

  • 我无法控制外部网址
【解决方案2】:

如果您无法控制外部 URL,并且它不支持 CORSJSONP,那么您最好的选择是为该服务编写一个服务器端代理方法。因此,在您的服务器上,您在自己的主机上公开一个新端点,该端点在服务器端代表您的客户端访问实际服务,并将结果返回给您的客户端。

【讨论】:

    【解决方案3】:

    对于使用 jsonp,服务器应该将返回类型与回调函数绑定。如果不是,您将无法从服务器获取数据。

    如果您使用的是 cors,服务器应该支持它。这意味着服务器应该设置,

    "Access-Control-Allow-Origin" header to "*"
    

    【讨论】:

      【解决方案4】:

      JS 或 jQuery 的问题在于,跨域数据可能无法实现,具体取决于浏览器或服务器或两者的组合,它们会禁止数据交换。这是许多浏览器和服务器上的安全策略。

      最好和最安全的选择是使用 JS 或 jQuery(Ajax 调用)与 PHP cURL 的组合,其中 cURL 将调用请求数据 xml/json 格式,然后发送回 Ajax 请求。

      请看下面的例子:

      在 JS/JQuery AJax 脚本中:

         $.ajax({
            url: 'php_script_with_cURL.php',
            dataType: 'json',
            data:'THE_DATA_OR_REQUEST',  
            type:'post',
            success: function(data) {
              if (data.expDate != null) {
                $('#trBlueLight').show();
              } else {
                $('#trBlueLight').hide();
              }
            }
         }); 
      

      然后在php文件中(必须和你的JS在同一个服务器): (您可以使用 url 字符串或 post 来请求数据)

          //USE POST IF YOU NEED TO SEND VARIOUS COMMANDS TO GET THE DATA BACK
          $post = $_POST;
      
          //INIT THE CURL CALL
          $curl = curl_init();
      
          curl_setopt_array($curl, array(
      
              CURLOPT_RETURNTRANSFER => 1,
      
              //this will tell the server how to return the data format
              CURLOPT_HTTPHEADER => array('Content-type: application/json'),
      
              //use the query string if require, if not just remove it
              CURLOPT_URL => 'http://THE_URL_HERE.COM?request_value=some_value',
      
              //use the post only if yo need to post values 
              CURLOPT_POST => 1,
              CURLOPT_POSTFIELDS => array(
                  value1 => $post['value1'],
                  value2 => $post['value2']
              )
              //alternative you can also pass the whole POST array
              //CURLOPT_POSTFIELDS => $post
          ));
      
          $data = curl_exec($curl);
      
          if(!$data){
              die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
          } 
      
          curl_close($curl);
      
          //echo the data that will be sent to the JS/JQuery Ajax call
          echo $data;
      
          //or if you need to do more processing with php  
          //$response = json_decode($data);
      

      希望这会有所帮助:) 快乐编码!

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-27
      • 2019-04-02
      • 2016-08-14
      • 1970-01-01
      • 2011-05-26
      • 2016-07-20
      • 2012-02-26
      • 2016-09-19
      相关资源
      最近更新 更多