下面这段内容会将后端获取的json数据,以一个div块的新式展示出来。下面代码是搭配bootstrap框架一起使用的。
$(document).ready(function () {
$("#submit").click(function () {
const qa = $("#question").val();
showItems(qa, true)
console.log(qa)
$.ajax({
url: "http://127.0.0.1:5000/qa",
method: "POST",
data: JSON.stringify({ question: qa }),
contentType: 'application/json',
success: function (response) {
console.log(response.message);
//将ajax的缓存数据取出显示
showItems(response.message, false);
console.log('刷新页面成功')
},
error: function () {
alert("提问为空,输入提问内容!");
}
});
});
function showItems(data, type=false) {
// 处理返回的 JSON 数据
var data = data;
// 将数据渲染到页面上
var $communication = $('#communication');
var $row = $('<div>').addClass('row text-white mb-1 ml-1');
if(type){
$row.append($('<div>').text("我:" + data));
}else{
$row.append($('<div>').text("服务助手桃子:" + data));
}
$communication.append($row);
}
});