jquery:ajax get请求不起作用

时间:2016-08-17 16:29:20

标签: jquery

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

http://localhost:8080/abc/employees

当我在浏览器中打开上面的url时,我得到了以下回复。

  

[{" firstName":" Hari Krishna"," id":1," lastName":&#34 ; Gurram"" permAddrees" {"区域":" Marthali""城市":"班加罗尔&#34 ;,"国家":"印度""状态":"卡纳塔克邦"}" tempAddrees":{& #34;区域":"电子   市""城市":"班加罗尔""国":"印度""状态&#34 ;: "卡纳塔克邦"}},{"的firstName":" PTR"" ID":2" lastName的&#34 ;: " PTR"" permAddrees" {"区域":"巴拉斯   纳加""城市":"海得拉巴""国":"印度""状态&#34 ;: "安得   邦"}" tempAddrees" {"区域":" BTM   布局""城市":"班加罗尔""国":"印度""状态&#34 ;: "卡纳塔克邦"}}]

以下是我的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>

当我点击按钮时,它会显示第一个警告框&#39;警告(&#34; Hello&#34;);&#39;,但不会执行回调函数中的警告框。任何人都可以帮我解决我的代码问题。 enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

简短回答

Safari允许它并且chrome不允许(CROSS ORIGIN REQUEST SHARING - CORS)。

实验:

让我们从“localhost”执行此html file“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

  

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

答案 1 :(得分:0)

您希望访问localhost以获取不属于locahost的文件

可以做两件事:

  1. 将文件作为localhost Web应用程序的一部分

  2. 进行正确的CORS设置,例如您正在使用JERSEY使用以下内容。

  3. How to handle CORS using JAX-RS with Jersey