【问题标题】:jquery: ajax get request not workingjquery:ajax获取请求不起作用
【发布时间】:2016-08-19 14:13:16
【问题描述】:

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

http://localhost:8080/abc/employees

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

[{"firstName":"Hari Krishna","id":1,"lastName":"Gurram","permAddrees":{"area":"Marthali","city":"Bangalore ","country":"India","state":"Karnataka"},"tempAddrees":{"area":"电子 City","city":"Bangalore","country":"India","state":"Karnataka"}},{"firstName":"PTR","id":2,"lastName":"PTR ","permAddrees":{"区域":"婆罗多 Nagar","city":"Hyderabad","country":"India","state":"Andhra Pradesh"},"tempAddrees":{"area":"BTM 布局","city":"Bangalore","country":"India","state":"Karnataka"}}]

以下是我的 jquery sn-p。

<!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");',但回调函数中的警报框没有执行。任何人都可以帮助我找出我的代码的问题。

【问题讨论】:

  • 当你调试这个时,它具体是如何失败的?服务器的响应是什么?有没有错误?
  • 嗨,David,添加了屏幕截图,正如您所看到的标题部分“内容长度为 244”即将到来。但是当我转到响应部分时,它是空的。
  • jquery 的路径是否正确?我检查了,它在 chrome 中运行良好(在给出 jquery 的路径后)。
  • 您的通话中有response,但您没有在任何地方定义它 - 您应该在控制台中收到错误消息。您实际上是在屏幕截图中调用/abc/employees/1。根据请求使用的标头(json / html),您的输出是否会有所不同?另外 - 请不要使用 alertconsole.log - alert 默认情况下会将所有内容都字符串化,因此它在调试中毫无用处(无论如何,您仍然应该在 Chrome 响应选项卡中有一个字符串)
  • 没有控制台报错CORS策略吗?

标签: jquery


【解决方案1】:

简答

Safari 允许,而 chrome 不允许(CROSS ORIGIN REQUEST SHARING - CORS)。

实验:

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

chrome 会发生什么?

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

Read about it here...

在 Safari 中会发生什么?

Safari 允许这种行为,因此您会从 http://www.google.com

证明

【讨论】:

  • 知道了。谢谢..:)
【解决方案2】:

看起来您想访问 localhost 以获取不属于 locahost 的文件

可以做两件事:

  1. 使文件成为 localhost Web 应用程序的一部分

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

How to handle CORS using JAX-RS with Jersey

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    相关资源
    最近更新 更多