Search code examples
javascriptjqueryajaxjsonjsonp

JSON issue with jQuery (JSONP)


I have a strange issue using jQuery and JSON, especially JSONP. My goal is to simply GET JSON data, but I always end up with the following error:

Uncaught SyntaxError: Unexpected token

Here is the code:

<script type="text/javascript">
     $(document).ready(function() {
      var myurl = "someurl";

     $.ajax({
            url: myurl,
            method: 'GET',
            contentType: 'application/javascript',
            dataType : 'jsonp',
            success: function(result){
                //Do something with JSON result
            }
    });
</script> 

And of course the JSON (raw format):

{"result":[{"targetView":"powerUsage","myData":{"someItems":["9","5","8"],"someItems2":[{"text":"protoText","currentRecord":"45.38","absolute":100}]}}]}

I tried the webservice with the Advanced Rest Client App in Google Chrome and it is working perfectly. I have no clue why this simple example gets this syntax error message.


Solution

  • Your Ajax code looks like fine. I think you are trying to make a Cross domain call as JSONP is a hack for dealing cross domain ajax call. If you Server code if ready for dealing with JSONP request then you must have send a callback parameter like

    ?callback=my_callback_method
    

    than you service will return result with a callback see below links for more details:

    https://learn.jquery.com/ajax/working-with-jsonp/
    http://stackoverflow.com/questions/11736431/make-cross-domain-ajax-jsonp-request-with-jquery