Skip to content Skip to sidebar Skip to footer

Retrieve JSON Data From Remote URL Via JQuery AJAX

I am using following code to get the data from URL. $.ajax({ url: 'http://183.77.251.173:90/api/function/getprice.aspx?code=1301&length=3M', success: function (data) {

Solution 1:

You cannot make a cross domain request unless you're using JSONP or CORS. The availability of those will depend on the API of the domain you are requesting information from.

This is a security feature of modern browsers known as the Same Origin Policy.


Solution 2:

Look up JSON with padding (or JSONP), since you use jQuery, you should take a look here: http://api.jquery.com/jQuery.getJSON/

Stolen example from that site:

<script>
(function() {
  var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
  $.getJSON( flickerAPI, {
    tags: "mount rainier",
    tagmode: "any",
    format: "json"
  })
  .done(function( data ) {
    $.each( data.items, function( i, item ) {
      $( "<img/>" ).attr( "src", item.media.m ).appendTo( "#images" );
      if ( i === 3 ) {
        return false;
      }
    });
  });
})();
</script>

EDIT:

An homemade example, using jquery.jsonp-2.4.0 for better error response (https://github.com/jaubourg/jquery-jsonp/downloads). But you can use plain jQuery as well.

On the client side, you need something like this:

$.jsonp({
    "url": target_url+"ping.php?callback=?",
    "success": function(data) {
        // print out data
    },
    "error": function(d,msg) {
        // error
    }
});

The ping.php file on target server:

<?php
    echo $_GET['callback'] . '(' . "{'response' : 'success'}" . ')';
?>

Solution 3:

As others have said you're getting error 0 is because the site is unreachable. Cross site issue is a reason. Of course so is an incorrect URL. If the URL you're trying to reach does work and is on a different domain than your site then yes you have a cross domain issue.

JSONP is going to be your only way to get it to work but there's drawbacks. Have a look at this post on SO for detailed explanation:

What is JSONP all about?

There's also a link in the article to http://www.json.org/JSONRequest.html. I haven't tried this so not sure if it works.

This should help you on your way.


Solution 4:

For cross-domain use $.getJSON().

$.getJSON('http://183.77.251.173:90/api/function/getprice.aspx?code=1301&length=3M', function(data){
alert(data.results[0].address_components[0].long_name);
});

Post a Comment for "Retrieve JSON Data From Remote URL Via JQuery AJAX"