通过Json文档创建超链接

Create Hyperlinks through Json Document

本文关键字:超链接 创建 文档 Json 通过      更新时间:2023-09-26

如果这是一个已经得到回答的非常简单的请求,并且我对javascript太不熟悉而无法理解,我提前道歉。

我想创建一个json目录,在HTML页面上显示为表,我希望其中一个单元格是超链接,但我不知道如何做到这一点。

这是我的json脚本:

"beer": [{
    "name": "NAME",
    "type": "TYPE",
    "company": "BREWERY",
    "website": "WWW.SITE.COM",
    "price": 6.00
}],

这是我的HTML脚本

<script>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest()}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","catalog.json",false);
xmlhttp.send();
json=JSON.parse(xmlhttp.responseText);
document.write("<table class=table table-bordered>");
var x=json.beer;
for (i=0;i<x.length;i++)
{ 
document.write("<tr><td>");
document.write(x[i].name);
document.write("</td><td>");
document.write(x[i].type);
document.write("</td><td>");
document.write(x[i].company);
document.write("</td><td>");
document.write(x[i].website);
document.write("</td><td>$");
document.write(x[i].price.toFixed(2));                                    
document.write("</td></tr>");
 }
document.write("</table>");
</script>

有人能帮助这个吗

首先,不要使用document.write。如果在页面加载完成后调用,它将擦除整个页面。最好使用DOM方法来添加新元素。

其次,AJAX(应该是(异步的,为什么要将false传递给.open()?(附言:我怀疑有人会用IE5/6访问这个网站,所以你可能会丢失new ActiveXObject(

// In 2014, this is all that's really needed
var xhr = new XMLHttpRequest;
// The callback to run when the request is done
xhr.onload = function(){
    // readyState 4 means the request is done, and 200 is HTTP OK
    if(xhr.readyState === 4 && xhr.status === 200){
        var json = JSON.parse(xhr.responseText),
            // The data we want to loop over
            x = json.beer,
            // This is how to make a new element
            table = document.createElement('table');
        // Set the classes
        table.className = "table table-bordered";
        // Loop over your data
        for(var i = 0; i < x.length; i++){
            // Create the HTML for this row
            var row = '<tr>' +
                '<td>'+x[i].name+'</td>' +
                '<td>'+x[i].type+'</td>' +
                '<td>'+x[i].company+'</td>' +
                // For a hyperlink, just use an `<a>` tag
                '<td><a href="'+x[i].website+'">'+x[i].website+'</a></td>' +
                '<td>'+x[i].price.toFixed(2)+'</td>'+
            '</tr>';
            // Let's just simply append to the table's innerHTML
            table.innerHTML += row;
        }
        // Add the table to the page
        document.body.appendChild(table);
    }
};
// This defaults to being *asynchronous*
xhr.open("GET","catalog.json");
// Start the request
xhr.send();