Search code examples
jqueryajaxjsonjsonp

jQuery ajax request using jsonp error


I'm writing an app and I need to access some json data in the client side from another server. Because of the cross domain issue I plan on using jsonp. jQuery allows me to do this using the $.getJSON() method, however, I have no way to tell if the method has failed (i.e., the server is not responding or something). So I tried the approach to get the JSON data using $.ajax instead. But it's not working and I don't know what to try. Here an example showing my issue:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
 <html>
 <head>
      <meta http-equiv="Content-type" content="text/html; charset=utf-8">
      <title>TEST</title>
      <script type="text/javascript" src="scripts/jquery-1.5.1.min.js"></script>
      <script type="text/javascript">
           $(document).ready(function() {
        $('#button_detect').click(function(){
            var feedApiAjax = 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=';
            var feedApiGetJSON = 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=';
            var feedUrl = 'http://www.engadget.com/rss.xml';

            $.ajax({
                url: feedApiAjax + feedUrl,
                datatype: 'jsonp',
                success: function(data) {
                    console.log('$.ajax() success');
                },
                error: function(xhr, testStatus, error) {
                    console.log('$.ajax() error');
                }
            });

            $.getJSON(
                feedApiGetJSON + feedUrl,
                function(data) {
                    console.log('$.getJSON success');
                });
        });
    });
      </script>
 </head>
 <body>
      <div id="button_detect">CLICK ME!!!!</div>
 </body>

If you create a web page with this code and click on the "Click Me" div you'll see that the $.getJSON request is working and the $.Ajax one is not. I've tried putting/removing the "callback=?" tg, used "jsonp" and "json" data types, but non of this worked.

Any idea on what might I be doing wrong?

Cheers!


Solution

  • I encountered this error before, and solved after using jquery-JSONP

    [Example]

    $.getJSON('http://server-url/Handler.ashx/?Callback=DocumentReadStatus',
      {
          userID: vuserID,
          documentID: vdocumentID
      },
      function(result) {
          if (result.readStatus == '1') {
              alert("ACCEPTED");
          }
          else if (result.readStatus == '0') {
              alert("NOT ACCEPTED");
          }
          else {
              alert(result.readStatus);
          }
      });