如何正确加载URL并访问其内容

时间:2016-07-26 22:29:43

标签: javascript jquery html json ajax

我正在尝试创建一个显示JSON内容的网页。我不想手工编写包含数百个条目的JSON文件,而是想加载给定URL的html并将其内容转换为JSON文件。

我对javascript和jquery很新,所以我做了一些练习网页来强化我学到的东西。对于本练习项目,我想访问此网页:http://dogtime.com/dog-breeds,遍历并显示其内容中的一些元素。 我坚持的是如何从给定网址中检索html。

我目前正在尝试此代码:

//When the document is ready
$(document).ready(function() {
    //Use ajax to load this webpage
    $.get("http://tired.com/", function(data) {
        //Load its data into the data variable
        var data = $(data);
        //Put the webpage into the variable with id "div"
        $("#div").html(data);
    });
})

但是在控制台中我收到错误:

" XMLHttpRequest无法加载http://tired.com/。 No' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' null'因此不允许访问。"

我在这篇文章上做了一些阅读:"No 'Access-Control-Allow-Origin' header is present on the requested resource"但我并不真正理解如何从中获得解决方案。我收集的一些可能的解决方案可能是:

  1. 在Windows中,将此命令粘贴到运行窗口中:

    chrome.exe --user-data-dir =" C:/ Chrome开发者会话" - 禁用网络的安全性

  2. 这似乎是一种不能长期工作的创可贴修复。

    1. 使用CORS:http://www.html5rocks.com/en/tutorials/cors/
    2. 这只有在客户端和服务器都支持CORS时才有效吗?我也无法理解在何处放置/如何使用此代码,因为只显示了功能片段,并且示例似乎无法正常工作。

      1. 下载HTML页面并解析它们。
      2. 同样,这似乎是一个避免问题的解决方案。

        这是我的全部代码:

        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1">
        
            <link href="bootstrap-3.3.6-dist/css/bootstrap.min.css" rel="stylesheet">
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
            <!--JSON file where I'll be storing some content-->
            <script src="breeds.js"></script>
        </head>
        
        <script>
            //When the document is loaded
            $(document).ready(function() {
                //Use Ajax to load the webpage
                $.get("http://tired.com/", function(data) {
                    //Load the webpage into the data variable
                    var data = $(data);
                    //Load the html from the webpage into the element with id "div"
                    $("#div").html(data);
                });
            })
        </script>
        
        <body>
            <div id="div"></div>​
        </body>
        </html>
        

        我非常感谢如何使这段代码有效。谢谢!

        编辑:所以我使用Python的BeautifulSoup创建了我的JSON文件,但我无法使用javascript来阅读它:

        $.getJSON("breeds.json", function(json) {
                    console.log(json);
        }) 
        

        因为它导致与以前相同的XMLHttpRequest错误。我已使用http://www.freeformatter.com/json-validator.html验证了我的JSON文件是否正确创建。我能找到的唯一解决方案是将json文件更改为js文件,并将json内容转换为全局的hacky方法,例如:

        breeds = '{"dogBreeds": [{"size": "1", "shedding": "1", "link": "http://dogtime.com/dog-breeds/affenpinscher", "energy": "4", ....."Yorkshire Terrier", "intelligence": "3"}]}'
        

        然后我可以阅读:

        window.onload = function() {
            var obj = JSON.parse(breeds);
            console.log(obj.dogBreeds[0].breedName);
        }
        

        有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

需要在服务器上启用

CORS。如果服务器未设置它,您的浏览器将抱怨从其他来源请求资源。这是你的问题,一个来源是&#34; tired.com&#34;另一个来源是为您的HTML页面提供服务的网络服务器。

您需要了解这是您自身安全的一项非常重要的功能。正如您通过使用该特定参数启动CORS所建议的那样禁用Chrome会使您的代码运行,但同时又是一个巨大的安全漏洞。此外,它只适用于那些使用该选项启动浏览器的人,除了你之外可能没有人:)

如果您没有在服务器端设置CORS标题的选项,那么您就搞砸了。但是,您可能会发现一种从不关心CORS的其他环境中加载数据的方法,例如来自服务器(参见morecchia808的提案)。你还没有迷路:))

答案 1 :(得分:1)

正如您所提到的,解决方案是解析远程html(Beautiful Soup非常适用于此)并在服务器上将其序列化为JSON。

最后一件事:您将继续获得相同的&#34; No&#39; Access-Control-Allow-Origin&#39;标头出现在请求的资源上#34;如果您打开&#34; index.html&#34;则会出错直接在浏览器中输入文件。您需要在服务器上提供网页,或者只运行localhost。由于您已经在使用Python,最简单的方法是打开命令提示符,cd进入保存html文件的目录,然后运行以下命令:

    $ python -m SimpleHTTPServer

然后在浏览器中打开http://localhost:8000。 json应该加载得很好。