jquery:ajax 获取请求不起作用

标签 jquery

我正在尝试使用 get 请求调用以下网址。

http://localhost:8080/abc/employees

当我在浏览器中打开上述网址时,我收到以下响应。

[{"firstName":"Hari Krishna","id":1,"lastName":"Gurram","permAddrees":{"area":"Marthali","city":"Bangalore","country":"India","state":"Karnataka"},"tempAddrees":{"area":"Electronic City","city":"Bangalore","country":"India","state":"Karnataka"}},{"firstName":"PTR","id":2,"lastName":"PTR","permAddrees":{"area":"Bharath Nagar","city":"Hyderabad","country":"India","state":"Andhra Pradesh"},"tempAddrees":{"area":"BTM Layout","city":"Bangalore","country":"India","state":"Karnataka"}}]

以下是我的 jquery 片段。

<!DOCTYPE html>
<html>
    <head>
        <script src = "jquery-3.1.0.js"></script>
    </head>

    <body>  
        <h1>Click the below button to see the AJAX response</h1>
        <input type="submit" value="click here" id="button1" />

        <div id="placeHolder">

        </div>


        <script type="text/javascript">
            var jq = jQuery.noConflict();

            jq(document).ready(function(){
                jq("#button1").click(function(){
                    alert("Hello");
                    jq.get("http://localhost:8080/abc/employees", function(data, status){
                        alert(data + "" + status);
                        jq("#placeHolder").html(response);
                    });
                });
            });
        </script>
    </body>
</html>

当我单击按钮时,它显示第一个警报框“alert("Hello");”,但回调函数中的警报框未执行。任何人都可以帮我解决我的代码的问题吗? enter image description here

enter image description here

最佳答案

简短回答

Safari 允许,而 Chrome 不允许(跨源请求共享 - CORS)。

实验:

让我们执行来自此 html file 的请求从我们的“localhost”“www.google.com”

Chrome 中会发生什么?

在 chrome 中,不允许 CORS(跨域请求共享),因此它会阻止您这样做。

Chrome gives the error as show below for http://www.google.com

Read about it here...

Safari 中会发生什么?

Safari 允许这种行为,因此您会收到以下响应 <强> http://www.google.com

Proof I have added url as http://www.google.com, and hence this response comes

关于jquery:ajax 获取请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39001878/

相关文章:

JQuery 修改使其切换

javascript - jquery 显示/隐藏带有鼠标悬停的大图像

javascript - 访问控制允许来源 : JavaScript (jQuery) vs. Python (urllib2)

jquery - 如何确定ajax调用失败的确切原因?

javascript - 显示模式对话框 jquery

javascript - 在 .slideToggle() 之后改回 css

javascript - HTML5 放置事件子级被阻止

javascript - JQuery 点击/触发不起作用

javascript - 如何做回发 Javascript, jquery

javascript - 为什么onChange事件没有产生?