无法使用javascript将JSON响应转换为HTML表

时间:2017-08-19 13:13:16

标签: javascript java html jsp

我从servelet获取ajax请求的以下json响应,但无法将数据转换为表并在jsp中显示它。

[{
  "ordernumber": 123456,
  "slotservice": "Collection       ",    
  "deliverydate": "Jul 1, 2017"
}]  

下面是我执行ajax请求的javascript,

    function addData(){
    if(window.XMLHttpRequest) { //Assuming you're not on one of the old IEs.
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST","Order",true);        
    var formData = new FormData(document.getElementById('orderform'));
    xhttp.send(formData);
    console.log('This is Ajax request to the order controller');
    xhttp.onreadystatechange=function() {
        if (xhttp.readyState == 4 && (xhttp.status == 200)) {
            var myArr = JSON.parse(xhttp.responseText);
            console.log(JSON.stringify(myArr));
            var tr;
            for (var i=0;i<myArr.length;i++){
                tr = $('<tr/>');
                tr.append("<td>"+myArr[i].ordernumber+ "</td>");
                tr.append("<td>"+myArr[i].slotservice+ "</td>");
                tr.append("<td>"+myArr[i].deliverydate+ "</td>");
                $('ViewOrderResultContainer').append(tr);
                console.log
            }               
        }
        }       
        }
        else console.log('not working');
        }

以下是我的index.jsp

中定义的表格
    <div id="divOrderResultContainer">
        <table id="ViewOrderResultContainer" border=1>
    <thead>
        <tr>
            <th>OrderNumber</th>
            <th>ServiceType</th>
            <th>DeliveryDate</th>
        </tr>
    </thead>
    </table>
    </div>

任何人都可以解释我在这里做错了什么,我怎样才能得到预期的结果。

编辑1:我现在更新了我的servlet,但是它仍然没有在我的jsp中打印HTML表格响应

 function addData(){
  if(window.XMLHttpRequest) { 
    var xhttp = new XMLHttpRequest();       
    xhttp.onreadystatechange=function() {
        if (xhttp.readyState == 4 && (xhttp.status == 200)) {
            var jsonorderdata = JSON.parse(xhttp.responseText);
            for (x in jsonorderdata)    
                 txt += "<tr><td>" + myObj[x].ordernumber+ "</td><td>" + 
 myObj[x].slotservice+ "</td><td>" + myObj[x].deliverydate+ "</td>"
                 "</tr>";
             }
            document.getElementById("ViewOrderResultContainer").innerHTML = 
txt;
            }
            }   
        xhttp.open("POST","Order",true);        
        var formData = new FormData(document.getElementById('orderform'));
        xhttp.send(formData);
        }   
    else console.log('not working');
}

另外我的javascript给出了304:chrome中未修改的响应,有人可以帮我解决如何在jsp中获取表格。

1 个答案:

答案 0 :(得分:1)

$('ViewOrderResultContainer').append(tr);中缺少选择器。添加#以按ID

选择元素
$('#ViewOrderResultContainer').append(tr);