我正在学习AJAX,但无法找到如何引用从.json文件中获取的表中的特定行。实际上我想要点击行中相应的编辑按钮的相应数据。它应该显示在表格正下方的<p>
标记中。
继承我的剧本
<script>
function myFunction() //on click function to fetch data from json
{
var counter;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if(xhttp.readyState == 4 && xhttp.status == 200)
{
var data = JSON.parse(xhttp.responseText);
mydata(data);
}
};
xhttp.open("GET", "employee.json");
xhttp.send();
counter ++ ;
}
function mydata(data){ //data to be shown and fetch
var output = "<table>";
var output = "<th>Employee Code</th>" +
"<th>Name</th>" +
"<th>Joining Date</th>" +
"<th>Salary</th>"+
"<th>Edit</th>";
//var i in each items[i]
for(var i in data)
{
output += '<tr>' +
'<td>' + data[i].empcode + '</td>' +
'<td>' + data[i].name + '</td>' +
'<td>' + data[i].joining + '</td>'+
'<td>' + data[i].salary + '</td>' +
'<td>' + '<button onclick="edit()">Edit</button>' +
'</tr>';
}
output +="</th>" + "</th>" + "</th>" + "</th>" + "</th>";
output += "</table>";
document.getElementById('demo').innerHTML = output;
function edit(){
document.getElementById("para").innerHTML = data[1].empcode;
}
}
function edit(){ //edit function to display related data from json file. Right now i can only display data which i mentioned in editTextData().
var edit = new XMLHttpRequest();
edit.onreadystatechange = function(){
if(edit.readyState == 4 && edit.status == 200){
var editData = JSON.parse(edit.responseText);
editTextData(editData);
}
};
edit.open("GET", "employee.json", true);
edit.send();
}
function editTextData(textData){
document.getElementById("para").innerHTML = textData[2].empcode;
}
</script>
这是JSON数据:
[{
"empcode" : 1,
"name": "sid",
"joining" : "13 march",
"salary" : 60000
},
{
"empcode" : 2,
"name": "andrew",
"joining" : "15 march",
"salary" : 65000
},
{
"empcode" : 3,
"name": "blake",
"joining" : "18 march",
"salary" : 70000
}
]
这是html代码:
<h1>AJAX Employee</h1>
<div>
<table id="demo"> </table>
</div>
<button onclick="myFunction()" ">Fetch Info</button>
<p id="para"> </p>
答案 0 :(得分:0)
您的edit
处理程序可以确定单击了哪个按钮,它属于哪一行,以及是哪个empcode。关键是传递给编辑处理程序的this
值。
您正在分配内联处理程序,这不是理想的,因此您需要对该部分进行更改:
'<td>' + '<button onclick="edit(this)">Edit</button>'
现在按钮被作为第一个参数传递给edit,所以:
function edit(btn) { //edit function to display related data from json file.
// get the TR that this button is in
var tr = btn.parentNode.parentNode;
// get the collection of tds
var tds = tr.querySelectorAll("td");
// get the contents of the first TD, that should be the empcode
var empcode = tds[0].innerText;
// do whatever you need to with empcode, or the other values in this record
console.log("empcode = " + empcode + ", name = " + tds[1].innerText);
}