我正在尝试使用表中的json响应为每个ContactID和ContactName添加新行的contactTable。我正在接收数据到控制台,但当我尝试将数据插入到我的html文档中时,我得到每个的undefined
值。
HTML结果
<tr>
<th id="contactName"></th>
<th id="contactID"></th>
</tr>
<tr>
<td>undefined</td>
<td>undefined</td>
</tr>
的index.html
<table id="contactTable">
<tr>
<th id="contactName"></th>
<th id="contactID"></th>
</tr>
</table>
的script.js
$(document).ready(function () {
$.ajax({
url: 'https://api2.******.com/crm/v1/rest/taggroups/1/contacts',
type: 'GET',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
drawTable(JSON.stringify(data));
drawRow(JSON.stringify(data));
console.log(data);
// $('#contacts').html(JSON.stringify(data, null)); returns pretty json
{alert('Success! Enjoy your data!')};
},
error: function () { alert('Request failed'); },
beforeSend: setHeader
});
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(rowData) {
var row = $("<tr />")
$("#contactTable").append(row);
row.append($("<td>" + rowData.ContactName + "</td>"));
row.append($("<td>" + rowData.ContactID + "</td>"));
}
function setHeader(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ******');
xhr.setRequestHeader('content-type', 'application/json');
};
这是json响应的第一条记录
Object
TagMembers:Array(185)
[0 … 99]
0:
ContactID:2732270
ContactName:"First Last"
RecAdd:"/Date(1427853954000-0700)/"
RecAddUser:0
RecID:3
TagGroupID:1
您的数据看起来像这样:
var data = {
TagMembers: [
{ContactID:2732270,
ContactName:"First",
RecAdd:"/Date(1427853954000-0700)/",
RecAddUser:0,
RecID:3,
TagGroupID:4
},
{ContactID:2732275,
ContactName:"Second",
RecAdd:"/Date(1427853954000-0700)/",
RecAddUser:0,
RecID:4,
TagGroupID:5
},
{ContactID:2732277,
ContactName:"Third",
RecAdd:"/Date(1427853954000-0700)/",
RecAddUser:0,
RecID:5,
TagGroupID:5
}]
};
这意味着你应该发送到drowTable
函数而不是data
而不是JSON.stringify(data)
(不需要将对象转换为字符串),但data.TagMembers
:drawTable(data.TagMembers);
数组,这样你就可以循环对象并从中获取每个数据。并且也不需要额外调用drawRow(JSON.stringify(data));
它是多余的,因为你已经在drowTable
函数内调用它
事实证明我需要对qazxsw poi做一些改变
drawRow