我尝试将JSON数据发送到客户端。我测试了typeof dataJ
,并在控制台object
返回了dataJ
,并打印了dataJ=[object Object],[object Object]
。在客户端,它什么也不显示,并且警告XMLHttpRequest.responseText
是null
,textStatus
是错误消息,errorThrown
是null
。因为它没有说错误,所以我不知道我做错了什么。
服务器站点:
app.post('/myaction', async function (req, res) {
async function next_func(req, res) {
var myJson = await show();
return myJson;
}
dataJ = await next_func(req, res);
console.log("dataJ=" + dataJ);
console.log(typeof dataJ)
res.status(200);
res.contentType('application/json');
res.send(dataJ);
});
app.listen(8081, function () {
console.log('Server running at http://127.0.0.1:8081/');
});
async function show() {
var con = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: "aaaaaaaa",
database: "doto"
});
var sql = "select * from task_list";
resultsArray = [];
await new Promise((resolve, reject) => {
con.connect((err, connection) => {
if (err) return reject(err)
con.query(sql, (err, rows, fields) => {
if (err) return reject(err)
resolve(rows.forEach((row) => {
resultsArray.push({
detail: row.details,
status: row.status,
subject: row.subject
});
})
)
})
})
})
console.log("resultsArray" + resultsArray);
return resultsArray;
}
客户端站点:
$.fn.ajaxShow = function (st) {
xhrct = $.ajax({
type: 'POST',,
data: {
status: st
},
url: 'http://127.0.0.1:8081/myaction',
success: function (data) {
alert("function");
$('#tb').empty();
if (data != null) {
var fotoData = $.parseJSON(data);
$(fotoData).each(function (i, obx) {
alert("fotoData");
$('#tb').append('<tr>')
.append('<td>' + obx.detail + '</td>')
.append('<td>' + obx.status + '</td>')
.append('<td>' + obx.subject + '</td>')
.append('</tr>');
});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest: " + XMLHttpRequest.responseText);
alert("textStatus: " + textStatus);
alert("errorThrown: " + errorThrown);
}
});
}