2016-08-17 52 views
2

我想使用获取请求调用以下url。jquery:ajax获取请求不起作用

http://localhost:8080/abc/employees

当我在浏览器上面的URL打开,我得到以下答复。

[{ “名字”: “哈日克里希纳”, “ID”:1, “姓氏”: “Gurram”, “permAddrees”:{ “区域”: “Marthali”, “城市”:”班加罗尔“,”国家“,”印度“,”国家“,”卡纳塔克邦“,”tempAddrees“:{”area“:”Electronic City“,”city“:”Bangalore“,”country“ ,“state”:“Karnataka”}},{“firstName”:“PTR”,“id”:2,“lastName”:“PTR”,“permAddrees”:{“area”:“Bharath Nagar”城市“:”海得拉巴“,”国家“:”印度“,”国家“:”安得拉 Pradesh“},”tempAddrees“:{”area“:”BTM Layout“,”city“:”Bangalore“国家“:”印度“,”州“:”卡纳塔克邦“}}]

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

当我按一下按钮,它显示第一个警告框“警报(‘你好’);”,但不执行回调函数的警告框。任何人都可以帮我找出我的代码问题。 enter image description here

enter image description here

+0

当你调试这个,怎么专失败?服务器的回应是什么?有没有错误? – David

+0

嗨大卫,添加屏幕截图,当你看到标题部分'内容长度是244'即将到来。但是当我去回复部分时,它是空的。 –

+0

jquery的路径是否正确? 我检查过,它在Chrome中运行良好(在给出jQuery的路径之后)。 – cafebabe1991

回答

1

简短的回答

Safari允许它和Chrome不允许(CROSS ORIGIN REQUEST共享 - CORS)。

的实验:

让我们从这个html file“www.google.com”从我们“localhost” 的执行请求。

在Chrome中会发生什么?

在铬中,CORS(CROSS ORIGIN REQUEST SHARING)是不允许的,因此它会阻止你这么做。

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

Read about it here...

在Safari中会发生什么?

Safari允许这种行为,因此是像你想为你的文件,不是的locahost的一部分,访问本地主机你从 http://www.google.com

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

+1

明白了。谢谢..:) –