这段代码在Firefox中运行良好,但在我测试的所有其他浏览器中,我得到了错误"语法错误:JSON解析错误:意外的EOF"在if (this.readyState == 4 && this.status == 200)
行。 json-string看起来像这样:
[{"ID":"1","token":"1234","name":"Test Satio","matno":"11111","reg_date":"2017-10-24 00:00:00","last_active":"2017-10-24 00:00:00","user_id":"25"},{"ID":"3","token":"2232434","name":"Test Satio 2","matno":"44444","reg_date":"2017-10-23 00:00:00","last_active":"0000-00-00 00:00:00","user_id":"25"},{"ID":"5","token":"32233","name":"Test Satio 3","matno":"12","reg_date":"0000-00-00 00:00:00","last_active":"0000-00-00 00:00:00","user_id":"25"}]
JS-代码:
$(document).ready(function postData() {
var id = localStorage.getItem('user-id');
var token = localStorage.getItem('user-token');
var vars = "id=" + id + "&token=" + token;
var hr = new XMLHttpRequest();
var url = "../php/getUsers.php";
hr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) { //in this line I get the error
var data = JSON.parse(hr.responseText);
for(var i=0;i<data.length;i++){
var templateData = {
name: data[i].name,
id: data[i].id
};
var id=templateData['id'];
$.get('templates/user.htm', (function (templateData) {
return function(templates) {
var template = $(templates).filter('#user-template').html();
$('#user-container').append(Mustache.render(template, templateData));
}
})(templateData));
}
}
}
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.send(vars);
});
我需要更改以使此代码适用于所有浏览器?
谢谢,Lukas
答案 0 :(得分:1)
我认为您不需要为每个用户启动用户模板的请求,我认为您可以执行一次并保存它。
我已经简化了你的代码并改变了你的外部ajax以使用jquery。
$(document).ready(function postData() {
$.post({
url: "../php/getUsers.php",
data: {
id: localStorage.getItem('user-id'),
token: localStorage.getItem('user-token')
},
dataType: 'JSON',
success: function (data) {
// now get the template
$.get('templates/user.htm', function (templates) {
var template = $(templates).filter('#user-template').html();
// we have the template and userdata array
data.map(function (el) {
return {id: el.id, name: el.name};
}).forEach(function (templateData) {
$('#user-container').append(Mustache.render(template, templateData));
});
});
}
});
});