我需要使用ajax从数据库中获取一些数据。我正在使用Node JS和Express来处理路由。
这是后端代码:
router.get('/isAuth', ensureLoggedIn, (req, res) => {
Permit.find({}).populate('authBy').exec()
.then(permits => res.jsonp(permits))
.catch(err => res.send(err));
});
这是客户端:
const allPermits = document.getElementById('allPermits'),
table = document.querySelector('table tbody');
allPermits.addEventListener('click', getData);
function getData() {
let xhr = new XMLHttpRequest();
xhr.open('get', '/permits/isAuth', true);
xhr.onload = () => {
if (this.status == 200) {
let permitData = this.responseText;
let responseData = '';
permitData.forEach((permit) => {
responseData +=
`<tr class="dataRow">
<td>${permit.name}</td>
<td>${permit.destination}</td>
<td>${permit.fromD}</td>
<td>${permit.toD}</td>
<td>${permit.notes}</td>
<td>
<button class="deletePermit" data-id="${permit._id}"><i class="fa fa-trash"></i></button>
</td>
</tr>`;
})
table.innerHTML = responseData;
}
}
xhr.send();
}
问题是该行不起作用:
table.innerHTML = responseData;
。我也尝试了
console.log(responseData)
,但是除了ajax请求的成功消息外,我什么都没看到-https://image.prntscr.com/image/6Otihd6jSMWPRdoz4y6y9g.png;谢谢!
最佳答案
因为使用的是箭头功能,所以this
方法内的onload
不会引用请求对象,因此this.status === 200
绝不会
是真实的。请改用函数表达式。
有关更多信息,请参见
Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?
Methods in ES6 objects: using arrow functions
When should I use Arrow functions in ECMAScript 6?
关于javascript - 这个ajax请求出了什么问题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46497576/