通过Json Document创建超链接

时间:2014-06-04 14:27:33

标签: javascript json

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

我想创建一个在HTML页面上显示为表格的json目录,我希望其中一个单元格成为超链接,但我无法弄清楚如何做到这一点。

这是我的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>

任何人都可以帮忙解决这个问题。

1 个答案:

答案 0 :(得分:0)

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

其次,AJAX(应该是)是异步的,为什么要将false传递给.open()? (P.S.我怀疑有人会用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();