我尝试使用jQuery的.get功能获得2个URL,第一个链接工作正常,但第二个链接不会将数据附加到div。
//Locate the input box
var URL = $('#download');
//When button gets pressed
function downloadURL(){
//Get the URL from the input box
var downloadURL = URL.val();
//Get the contents of the JSON on the website linked
$.get(downloadURL,
//add it to the output div
function(data){
$("#output").append(data)
}
);
//Tell me that it has actually accepted the URL
alert(downloadURL);
}
<p> <input type="text" name="download" id="download" placeholder="Download URL"></p>
<button onclick="downloadURL()">Test</button>
<div id="output"></div>
我尝试过的2个网址是:https://raw.githubusercontent.com/TemporalReality/modpacks/master/packs/ingenuity.json和http://widget.mcf.li/mc-mods/minecraft/224791-blood-magic.json
任何想法为什么它适用于一个URL,而不是另一个?或者更好的方法呢?
答案 0 :(得分:2)
第二个网址将以object
而不是string
的形式返回。 $.append
需要DOM对象或字符串。
如果你真的想以这种方式追加它,你可以将其字符串化。
urls = [];
urls.push("https://raw.githubusercontent.com/TemporalReality/modpacks/master/packs/ingenuity.json");
urls.push("http://widget.mcf.li/mc-mods/minecraft/224791-blood-magic.json");
$(urls).each(function(i, item){
$.get(item, function(data){
console.log(typeof data, item); // <-- watch the console
if (typeof data === "object") {
data = JSON.stringify(data);
}
$("#output").append(data).append('<hr>');
});
});
假设您想要使用它做一些更有趣的事情,您可以单独保留对象并将字符串转换为JSON.parse
或$.parseJSON
的对象。
if (typeof data === "string") {
data = JSON.parse(data);
}
console.dir(data);