0

Currently, I have a url which renders data in json format.

url:

http://10.0.1.11/render?target=threshold(400,test)&from=-1mins&format=json&jsonp=?

when run in a browser gives me

?([{"target": "test", "datapoints": [[400, 1388755180], [400, 1388755190], [400, 1388755200], [400, 1388755210], [400, 1388755220], [400, 1388755230], [400, 1388755240]]}])

I would need the json result in a variable for further processing. I tried the following

foo
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$.getJSON("http://10.0.1.11/render?target=threshold(400,test)&from=-1mins&format=json&jsonp=?", function(result){
   //response data are now in the result variable
   alert(result);
});
</script>

I ideally would need:

var test = [{"target": "test", "datapoints": [[400, 1388755180], [400, 1388755190], [400, 1388755200], [400, 1388755210], [400, 1388755220], [400, 1388755230], [400, 1388755240]]}];

Where am i going wrong?

Vamsi Krishna
  • 475
  • 3
  • 9
  • 22
  • 2
    What's wrong with the `result` variable? What processing do you want to do? Do you understand how [JSONP](https://en.wikipedia.org/wiki/JSONP) works and that is has nothing to do with JSON? – Bergi Jan 03 '14 at 13:43
  • I forgot to add the source,so I was missing the alert. On adding the source, My alert states [object Object] – Vamsi Krishna Jan 03 '14 at 13:47
  • 1
    You don't say what your problem is. My guess is that you rely in `alert()` to debug, thus get all your data cast to strings. Find your browser's console instead. – Álvaro González Jan 03 '14 at 13:47

1 Answers1

1

You need to interpret the request as jsonp rather than json. jsonp is like json, but it's json wrapped in a method-call. (see: What is JSONP all about?)

You can use something like:

    <script>
    function myCallback(json_data){
        //do something with json_data!

    }
    </script>
    <script type="text/javascript" src="http://10.0.1.11/render?target=threshold(400,test)&from=-1mins&format=json&jsonp=myCallback"></script>

or

   <script>
        $(document).ready(function(){
            $.ajax({
                url: 'http://10.0.1.11/render?target=threshold(400,test)&from=-1mins&format=json',
                dataType: 'jsonp',
                success: function(json_data){
                        //do something with json_data!
                    }
                }
            });
        })
    </script>

(examples adapted from the linked post)

Community
  • 1
  • 1
ljgw
  • 2,751
  • 1
  • 20
  • 39
  • I'd personally advise against using jQuery yet doing AJAX stuff manually for no apparent reason. – Álvaro González Jan 03 '14 at 13:52
  • @ÁlvaroG.Vicario, What do you suggest? I am trying to add tabulation functionality to Giraffe https://github.com/kenhub/giraffe/blob/master/js/giraffe.js. I have the following function http://jsfiddle.net/arg9X/81/ – Vamsi Krishna Jan 03 '14 at 14:19