[英]ajax post working on chrome but not working on firefox and safari
[英]Ajax script only working in Firefox (not working in Chrome, Safari, Edge,…)
該代碼在Firefox中工作正常,但是在我測試過的所有其他瀏覽器中, if (this.readyState == 4 && this.status == 200)
出現錯誤“ SyntaxError:JSON Parse error:Unexpected EOF”。 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);
});
為了使此代碼在所有瀏覽器中都能正常工作,我需要更改什么?
謝謝,盧卡斯
我認為您無需為每個用戶觸發對用戶模板的請求,我認為您可以一次保存該模板。
我已經簡化了您的代碼,並更改了外部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));
});
});
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.