简体   繁体   中英

cross domain request data using pure javascript

I am trying to access an external url which returns json data and based on one of the value in that data I need to hide a table row. I have tried several options to do this with jsonp, jquery and ajax but nothing seem to work. YQL is working for me but I can't use outer Service as the code need to be independent. Please someone let me know how I can make this work with javascript

This is one approach I have tried

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

This is another approach I have tried. same issue unauthorized - 401

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

I have even tried to get data from url using jsp with and that also causing some permission issue

Do you control the external url? Because you can do:

On your local page:

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

And then on http://www.include.me/remote.php (or whatever is returning JSON) you would have it return

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

And then back on your local page:

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

Which will then include the script, which simply tells it to run your already defined function with the data it provides.

If you can't control the external URL, and it doesn't support CORS nor JSONP , then you best option is to write a server side proxy method for the service. So on your server, you expose a new endpoint on your own host that on the server side access the real service on your clients behalf, and returns the result to your client.

For using jsonp, the server should bind the return type with a callback function. If it not, you cannot get the data from server.

If you are using cors, server should support that. Which means server should set,

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

The issue with JS or jQuery is that crossdomain data may not be possible depending on the browser or server or a combination of both that prohibits the data exchange. This is security policy on many browsers and servers.

The best and safest choice is using a combination of JS or jQuery (Ajax call) with PHP cURL where the cURL will make the call requesting the data xml/json format and then sent back to the Ajax request.

Please take a look at the following example:

In the JS/JQuery AJax script:

   $.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();
        }
      }
   }); 

and then in the php file (must be in the same server as your JS): (you can use url string or post to request the data)

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

Hope this helps :) Happy coding !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM