2015-12-03 126 views
1

我有2个URL,我尝试使用jQuery的.get功能,第一个链接完美运行,但第二个不会将数据附加到div。jQuery - .get适用于1个URL,但不适用于另一个

//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, 
 
\t //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.jsonhttp://widget.mcf.li/mc-mods/minecraft/224791-blood-magic.json

任何想法,为什么它为一个URL,而不是其他?或者更好的方法来做到这一点?

+0

上面我说的那个人是正确的。解决这个问题的唯一方法是使用类似于php或服务器端脚本的方式从服务器请求数据。 – Chris

回答

2

第二个URL将作为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); 
+0

+1,你实际上对测试这两个链接感到困扰,而且它们都似乎工作,只是一个不会将自己标识为JSON,因此它不会被jQuery解析,因此该字符串未解析。有一个更简单的方法来解决这个问题,只需添加一个数据类型作为'$ .get'的最后一个参数,然后jQuery就会像这样解析它 - > http://jsfiddle.net/a1n635ed/ – adeneo

+0

非常感谢,这是完美的<3 – Jordan

+0

很高兴它帮助。和好点@adeneo。如果你已经使用jQuery,不妨去试试。 – Will

相关问题