我尝试将节点js中的JSON发送给客户端,但是它不起作用

时间:2018-09-06 06:42:58

标签: javascript jquery node.js

"PHP versions below 7.0 are not supported"

我尝试将JSON发送给客户端,但是客户端警报XMLHttpRequest为Server site: app.post('/myaction', async function(req, res) { async function next_func(req, res){ var st = req.body.status; var myJson = await show(); return myJson; } dataJ = await next_func(req, res); try { dataJson = JSON.parse(JSON.stringify(dataJ)); } catch (e) { console.log("parse error"); } if( isJSON(JSON.stringify(dataJ))) console.log("be Json "); else console.log("not Json "); console.log("send JSON : "+JSON.stringify(dataJ)); console.log("type JSON : "+typeof JSON.stringify(dataJ)); console.log("dataJson : "+dataJson); console.log("type dataJson : "+typeof dataJson); res.status(200); res.setHeader('Content-Type', 'application/json'); res.send(dataJson); }); 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} ); }) ) }) }) }) return resultsArray; } function isJSON(str) { try { return (JSON.parse(str) && !!str); } catch (e) { return false; } } Cleint site $.fn.ajaxShow = function(st) { xhrct = $.ajax({ type: 'POST', dataType: "json", 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); } }); } ,textStatus:error和errorThrown为null。在控制台上,它显示'be Json'和dataJson的类型是一个对象并发送JSON:

null

请帮助我

1 个答案:

答案 0 :(得分:2)

尝试添加内容类型并对要发送的对象进行字符串化:

 data: JSON.stringify({status : st}),
 contentType: "application/json"