使用纯javascript跨域请求数据

时间:2013-05-09 05:01:56

标签: javascript cross-domain

我正在尝试访问一个返回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获取数据,这也导致了一些权限问题

4 个答案:

答案 0 :(得分:0)

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

在您的本地页面上:

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);

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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

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

答案 3 :(得分:-1)

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 string或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);

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

相关问题