我正在尝试使用https://www.jqueryscript.net/form/engage-audience-conversational-chatty.html中的示例插件来自定义jquery聊天机器人。
我使用以下代码:
var tags=[];
$.ajax({
type: "POST",
/*method type*/
url: "sample.jsp",
dataType: "text",
data: "usrname=" + $('#uname').val(),
async: false // To push values to an array
}) //ajax
.done(function(data) {
alert(data); // it displayed all the content which is needed for the array correctly
tags.push(data);
})
.fail(function(f) {
alert("Chatbot Module fetch failed!!");
});
我从java方法中以字符串的形式检索'data‘:
如果我在javascript函数中直接使用下面这行代码,它工作得很好:
function addArr() {
tags.push({type: 'input', tag: 'text', name: 'converse', 'chat-msg': 'Hi Welcome!!'},);
}
但是,如果我尝试将字符串推入数组,它将不起作用。我将字符串内容框定如下:
// java code:
result = "{type: 'input', tag: 'text', name: 'converse', 'chat-msg': 'Hi Welcome!!'},"
return result;
发布于 2020-02-01 09:33:54
那么,您尝试做的是将js对象推送到一个数组,但是您得到的是一个JSON字符串作为响应?如果是这种情况,您可以将dataType更改为"json“。
$.ajax({
type: "POST",
/*method type*/
url: "sample.jsp",
dataType: "json", // dataType -> json
data: "usrname=" + $('#uname').val(),
async: false // To push values to an array
})
另一种方法是在成功时解析字符串,但更简洁的方法是更改dataType。
var tags=[];
$.ajax({
type: "POST",
/*method type*/
url: "sample.jsp",
dataType: "text",
data: "usrname=" + $('#uname').val(),
async: false // To push values to an array
}) //ajax
.done(function(data) {
tags.push(JSON.parse(data)); // Parse string JSON.parse(data)
})
.fail(function(f) {
alert("Chatbot Module fetch failed!!");
});
发布于 2020-02-01 12:53:43
我用过dataType:" json ",// dataType -> json
然后我使用JSONObject和JSONArray来创建数组。
enter code here
JSONObject dao = new JSONObject();
JSONObject dao1 = new JSONObject();
ResultSet rs = null;
JSONArray ja = new JSONArray();
String modules="";
String result ="";
String modl="";
String qry = "";
qry = "SELECT color FROM allmodules";
rs = db1.execSQL(qry);
while( rs.next() )
{
modules = rs.getString("color") ;
dao1.put("value", modules);
dao1.put("text", modules);
ja.add(new JSONObject(dao1));
}
dao.put("type","input");
dao.put("tag", "radio");
dao.put("name","module");
dao.put("chat-msg", "Hi Welcome" + user + "!!" + " Choose any of the color given below!!");
dao.put("children",ja);
return dao.toString();
https://stackoverflow.com/questions/60015492
复制