相同的域策略jQuery

时间:2012-08-23 17:14:22

标签: javascript jquery ajax

我曾问过一个问题,为什么大多数ajax解决方案都涉及一些像PHP这样的后端语言。

我被告知这是因为由于相同的域策略,Web浏览器不允许完整的javascript / jquery解决方案。但是下面的代码绝对运行良好:

<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>

这段代码不应该运行吗?我不明白。

谢谢, 吉姆

2 个答案:

答案 0 :(得分:2)

dataType: "jsonp",

JSONP用于绕过相同的原始策略。

以下是有关详细信息的链接 - http://www.ibm.com/developerworks/library/wa-aj-jsonp1/

另外,请注意,服务器也可以只允许访问。这是大多数第三方API供应商所做的。 - http://enable-cors.org/

答案 1 :(得分:1)

只有jsonp请求跨域工作。你的做法是正确的!

1)您无法访问其他域上的DOM元素或JavaScript对象(例如,在iframe中) 在这里看到我的答案:How can I create a function in another frame?

2)我们曾经做过这样的事情(参见我的回答),从JS到PHP进行沟通。 JavaScript: How do I create JSONP?

相关问题