使用Javascript/AJAX中的GetElementById无法获取表格数据
问题描述:
这是我的JavaScript函数。使用Javascript/AJAX中的GetElementById无法获取表格数据
var ajaxRequest = new XMLHttpRequest;
ajaxRequest.open("GET", "crudops.aspx?StudentId="+id+"&StudentName="+name+"&operation=insert", false);
ajaxRequest.send(null);
document.getElementById("TableDiv").innerHTML = ajaxRequest.responseText;
var t = document.getElementById("TableDiv").innerHTML;
alert(t);
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = id;
cell2.innerHTML = name;
这里是里面有什么t。
<table id="studenttable" cellpadding="5"><tbody><tr><th>Student Id</th><th>Student Name</th> ... </table>
但我无法读取表到使用类似
var table = t.getElementbyId("studenttable");
如何读取表,并追加行的变量? 帮我提建议。
答
var t = document.getElementById("TableDiv").innerHTML;
var table = t.getElementById("studenttable");
t varible shoud是一个元素,而不是一个字符串。尝试删除.innerHTML;
。
答
字母“d”需要大写。
var table = t.getElement B yId(“studenttable”);
答
由于异步请求的需要分配一个回调函数来处理响应数据,而不是期待的回应立即
var xhr = new XMLHttpRequest;
xhr.onreadystatechane=function(){
if(xhr.readyState==4 && xhr.status==200){
document.getElementById("TableDiv").innerHTML = xhr.response;
var t = document.getElementById("TableDiv").innerHTML;
alert(t);
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = id;
cell2.innerHTML = name;
}
};
xhr.open("GET", "crudops.aspx?StudentId="+id+"&StudentName="+name+"&operation=insert", true);
xhr.send(null);
+0
我还没有注意到使用“false”作为同步标志 – RamRaider
答
- 设置XHR性质
async
到true
(或者你可以省略) - 使用
onreadystatechange
回调 - 不要
innerHTML
指DOM元素使用DOM节点元素对象,而不是
var id = "123",
name = "This Is A Name";
var XHR = new XMLHttpRequest(),
method = "GET",
url = "crudops.aspx?StudentId="+id+"&StudentName="+name+"&operation=insert";
XHR.open(method, url, true); // << or omit async (anyway defaults to true)
XHR.onreadystatechange = function() {
if(XHR.readyState === XMLHttpRequest.DONE && XHR.status === 200) {
document.getElementById("TableDiv").innerHTML = XHR.responseText;
// Use meaningful var names
// var tableWrapper = document.getElementById("TableDiv").innerHTML;
// BTW since at this point your table is (hopefully) in the DOM
// you can go get it directly
var table = document.getElementById("studenttable");
if(!table) return; // Do nothing if no such Element in DOM
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = id;
cell2.innerHTML = name;
}
};
XHR.send();
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open
您能得到什么,如果你'的console.log(ajaxRequest.responseText);'? – caramba
整个'TableDiv' HTML代码@caramba –
'var row = table.insertRow(0);'什么是'table'?你只有't',而不是'table'。 'innerHTML'也返回一个字符串! –