2

I had asked a question regarding why most ajax solutions involve some back-end language like PHP.

I was told it was because of the fact that a web browser does not allow a complete javascript/jquery solution due to same domain policy. Yet the code below absolutely runs fine:

<script type="text/javascript">
        $(document).ready(function () {
            $("#1").click(function () {

                $.ajax({
                    type: "GET",
                    url: "http://api.wunderground.com/api/ac7e64a2f6e2d440/geolookup/conditions/q/IA/Cedar_Rapids.json",
                    dataType: "jsonp",
                    success: function (parsed_json) {
                        $('div').html("Current temperature in " + parsed_json.current_observation.temp_f);
                        alert(parsed_json.location.city);
                        var location = parsed_json['location']['city'];
                        var temp_f = parsed_json['current_observation']['temp_f'];
                        alert("Current temperature in " + location + " is: " + temp_f);
                    }
                });

            });

        });
</script>

So is this code not supposed to run? I don't get it.

Thanks, Jim

Eli
  • 14,779
  • 5
  • 59
  • 77
jim dif
  • 641
  • 1
  • 8
  • 17

2 Answers2

2

dataType: "jsonp",

JSONP is used to get around the same origin policy.

Here's a link for more information - http://www.ibm.com/developerworks/library/wa-aj-jsonp1/

Also, please note that servers can simply allow access as well. This is what most 3rd party API vendors do. - http://enable-cors.org/

JohnP
  • 49,507
  • 13
  • 108
  • 140
1

only jsonp requests work cross-domain. Your way of doing it is correct!

1) you can't access DOM elements or JavaScript Objects on other domain (in iframe for example) see my answer here: How can I create a function in another frame?

2) we used to do things like this (see my answer) to communicate from JS to PHP and back. JavaScript: How do I create JSONP?

Community
  • 1
  • 1
Scherbius.com
  • 3,396
  • 4
  • 24
  • 44