我正在嘗試創建一個顯示JSON內容的網頁。我不想用手寫數百個條目來編寫JSON文件,而是希望加載給定網址的html並將其內容轉換爲JSON文件。如何正確加載URL並訪問其內容
我對javascript和jquery很新,所以我正在做一些練習網頁以加強我所學到的東西。對於這個練習項目,我想訪問這個網頁:http://dogtime.com/dog-breeds,遍歷並顯示其內容中的一些元素。 我堅持的是如何從給定的URL中檢索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/無「訪問控制允許來源'標題出現在請求的資源上,因此不允許Origin'null'訪問。「
我在這篇文章上做了一些閱讀:"No 'Access-Control-Allow-Origin' header is present on the requested resource"但我並不真正瞭解如何從中獲得解決方案。我收集了一些可能的解決方案可能是:
在Windows中,在運行窗口中粘貼此命令:
的chrome.exe --user-data-dir來= 「C:/ Chrome瀏覽器開發會議」 - -disable-web-security
這看起來像是一個不能長期工作的創可貼。
- 使用CORS:http://www.html5rocks.com/en/tutorials/cors/
- 下載HTML頁面並解析它們。
這是否只是工作,如果客戶端和服務器支持CORS?我也無法理解在哪裏放置/如何使用此代碼,因爲只顯示了函數片段,並且該示例似乎不起作用。
再次,這似乎是一個修復,可以避免這個問題。
這是我的代碼全部:
<!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錯誤前。我已驗證我的JSON文件是通過使用http://www.freeformatter.com/json-validator.html正確創建的。我能找到的唯一解決辦法是改變JSON文件到一個js文件,並且json的內容轉換成的哈克方式的全局,如:
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);
}
有沒有更好的方法來做到這一點?
您是否可以訪問要加載的URL所屬的服務器? – nixkuroi
如果您無法訪問託管您請求的URL的服務器,我建議使用服務器端解決方案(想起Python的美麗湯)從這些頁面獲取HTML,將其序列化爲JSON,然後將其提供給您的客戶。然後你的jQuery ajax調用可以請求來自同一個域的數據。 – morecchia808
你是什麼後端?我們會推薦你的東西 –