1

There are a lot of questions on SO about this sort of issue, eg:

Basic example of using .ajax() with JSONP?

But I can't seem to get any of them to return a sensible result.

I have been given an API call procedure to use (I believe it is based on the REST API) to retrieve values from a server, it looks like this:

http://stage.xxxxxxxxx.co.uk/Search/?q=london&srid=3857&format=json&api_key=xxxxxxxxxxxxxxxxxxxxxxxx

I've had to use xxxxx for obvious reasons, particularly for the key.

Submitting this to a web browser such as IE returns what appears to be a JSON object, looks like this:

{
    "features": [
        {
            "id": 2728329,
            "name": "LONDON",
            "city": null,
            "county": "LONDON",
            "address": "LONDON",
            "address_2": null,
            "display_text": "LONDON LONDON",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    -16004.689675,
                    6708355.967961
                ]
            },
            "lon": -16004.689675330877,
            "lat": 6708355.967960811
        }
    ]
}

The trouble I'm having is trying to retrieve this object as a JSON object (or even a string) using jQuery.

I quickly discovered that XMLHttpRequest doesn't work because of using the 'same domain' so I turned to JSONP, but I'm failing to understand how to use it properly.

For example, I have this:

$.getJSON("http://stage.xxxxxxxxxxx.co.uk/Search/?q=london&srid=3857&format=json&api_key=xxxxxxxxxxxxxxxxxxxxxxxxx?callback=?", function(result) {
    format: "json"
}); 

Where do I go from here to get the JSON object mentioned above?

Community
  • 1
  • 1
Single Entity
  • 2,925
  • 3
  • 37
  • 66
  • 1
    I think you've confused yourself. JSON is a means of serialising an object to a string. What you've received back has already been deserialised to an object for you by jQuery. If you are receiving that object in response to your request then your code appears to be working, you simply need to access the properties of the object to perform whatever logic you require. – Rory McCrossan Jan 22 '15 at 13:36
  • My code doesn't get the object, or a string back, the output I showed is from IE from me entering the query directly into the URL. I would like to get the same, or ideally an object in my jquery code. – Single Entity Jan 22 '15 at 13:43

2 Answers2

3

I quickly discovered that XMLHttpRequest doesn't work because of using the 'same domain' so I turned to JSONP, but I'm failing to understand how to use it properly.

You can't use JSONP unless the endpoint you're callling supports it, and you tell it that that's what you're requesting. That's because it has to send back a different format (JSONP rather than JSON).

JSON and JSONP are fundamentally different, despite looking very nearly the same. A JSON response is a textual format defining data according to the JSON standard (loosely documented at http://json.org, more formally there's an RFC somewhere); a JSONP response is a function call passing in a JavaScript object, which is meant to be executed as script code.

Here's an example of a simple theoretical JSON query and response:

Request: http://example.com/give-me-deh-stuff?format=json&id=foo

Response:

{"stuff": {"foo":"bar"}}

Here's an example of an equivalent simple theoretical JSONP query and response, where you don't specify the callback name:

Request: http://example.com/give-me-deh-stuff?format=jsonp&id=foo

Response:

callback({"stuff": {"foo":"bar"}})

..and one where you do:

Request: http://example.com/give-me-deh-stuff?format=jsonp&callback=_cb12345&id=foo

Response:

_cb12345({"stuff": {"foo":"bar"}})

If the endpoint supports JSONP, jQuery will happily provide the callback function and set the argument on the URL, you just have to tell it what the argument is called (it assumes callback if you don't, which many APIs use and many others don't).

Note now the JSONP versions are calling a function (callback or _cb12345). Your code (or jQuery) ensures there's a function with that name available at global scope, and then you append the script with the request URL, and it runs when it comes back. Which is how JSONP avoids the Same Origin Policy.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thank you very much, but may I ask how IE would work this out? It doesn't necessarily know the callback name does it? Yet it manages to parse the JSON query. – Single Entity Jan 22 '15 at 13:42
  • 1
    @SingleEntity: Pasting a URL into a web browser's address bar is not subject to the SOP; using that same URL in an XHR request *is*. That's why you can do it by pasting into the address bar, but not via XHR. – T.J. Crowder Jan 22 '15 at 13:43
  • 1
    @SingleEntity: If the endpoint you're calling is intended to be called directly from end user browsers as part of other people's (e.g., your) web sites, they'll probably support JSONP, just look at the docs and/or ask them. If the endpoint is meant to be consumed only from code running on *their* site, or only from servers, they probably don't. – T.J. Crowder Jan 22 '15 at 13:45
  • Thank you very much, I'll get in contact with them to find out. – Single Entity Jan 22 '15 at 13:46
-1

it can be done using JSON.NET by JsonSchema object

Below is a simple example for retriving data from JSON

string schemaJson = @"{
  'description': 'A person',
  'type': 'object',
  'properties': {
  'name': {'type':'string'},
  'hobbies': {
  'type': 'array',
 'items': {'type':'string'}
  }
 }
}";

JsonSchema schema = JsonSchema.Parse(schemaJson);

Console.WriteLine(schema.Type);
// Object

foreach (var property in schema.Properties)
{
Console.WriteLine(property.Key + " - " + property.Value.Type);
}
// name - String
// hobbies - Array

This is just a simple approach to get data... there are many ways to get data for more details Click here for documentaion of JSON.NET to work on JSON Data

i hope my answer is helpful

  • Thank you for your answer, it is very useful should I get the string and require it to be parsed. I appreciate your answer – Single Entity Jan 22 '15 at 15:12