TLD
TLD

Reputation: 8135

Parsing json file when using jsonp with jquery

Json file:

{
"weather": [
    {
        "location": "G",
        "temp": "9"
    },
    {
        "location": "L",
        "temp": "6"
    },
    {
        "location": "W",
        "temp": "10"
    }
]

}

Script

<script type="text/javascript">
                    // <![CDATA[
                    $(document).ready(function() {
                        var url =  ".../Json.php";
                        $.getJSON(url + "?callback=?", null, function(weather) {
                            for(i in weather) {
                                location = weather[i].location;
                                temp = weather[i].temp;
                                $("#footer").append(location.text + temp.text+"<hr />");
                            }
                        });
                    });

                    // ]]>
</script>


Can somebody show me where I did incorrectly? Is that because the json url I used belongs to different domain ? I tried using jsonp but it still doesn't work,....
Thank you very much.
P/S: Where I got the Jsonp idea Example and I can't configure the server, it's forbidden.

Upvotes: 0

Views: 233

Answers (2)

Guffa
Guffa

Reputation: 700800

The problem is that you are requestion JSONP and getting JSON. It will just be parsed and silently ignored as there is no function call to do anything with the object.

Your JSONP response should have a function call around the object, like this:

func({
  "weather": [
    {
        "location": "G",
        "temp": "9"
    },
    {
        "location": "L",
        "temp": "6"
    },
    {
        "location": "W",
        "temp": "10"
    }
  ]
});

Use the value of the querystring parameter callback as the function name instead of func in the example above.


Then when you get the result, it's not an array, it's an object that has a property that is an array. Use the weather property to get the array:

for(i in weather.weather)

Upvotes: 1

StaticVariable
StaticVariable

Reputation: 5283

You cannot use this

var url =  ".../Json.php";

You cannot make call to other domain url

In spite of the power of the XMLHttpRequest API, its usage is limited by the “same-origin” policy. What this means is that the hostname of the url you are sending the XMLHttpRequest cannot be different from the hostname of the web server.

Upvotes: 0

Related Questions