使用给定的URL和密钥将JSON对象提取到jQuery ajax中

Fetch JSON object into jQuery ajax with given URL and key

本文关键字:提取 对象 JSON jQuery ajax 密钥 URL      更新时间:2023-09-26

远程服务器上的 API 将返回一个 HTTP 200 响应,其中包含关键"联系人"可用的所有联系人的 JSON

"contacts" : [{
    "id" : "1"
    "contact_name" : "Bob"
    "contact_phone" : "9876543210",
    "contact_email" : "bob@example.com"
}] 

该 API 支持使用 CORS 的跨域请求,并处理原版 Ajax 请求(无需实现 JSONP 回调)。到目前为止我的代码;

<script>
    $(document).ready(function(){
        $.ajax({
            type: 'GET',
            url:  'http://ui-proj.practodev.in/contacts',
            dataType: 'json',
            success: function(data){
                $("#contacts").html(data);
            }
        });
    });
</script>
<div id="contacts"></div>

但是我无法在我的页面中获取 JSON 数据。请告诉我我可能错的地方。

使用 Fiddler 查看该请求的响应,我发现您缺少授权标头:

HTTP/1.1 401 UNAUTHORIZED
Server: nginx/1.4.1
Date: Sat, 02 Nov 2013 13:44:39 GMT
Content-Type: application/json
Content-Length: 43
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: X-USER
{
  "X-USER": "Missing X-USER in headers"
}

您可以查看如何在 http://api.jquery.com/jQuery.ajax/中添加标头