我是JavaScript和AJAX的新手。我收到以下错误:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 92 of the JSON data in javascript
我在谷歌搜索了很多,但我找不到解决方案。还有一件事,如果我在数据库中只有一个记录,我的代码工作正常;但如果我在数据库中插入另一行,我会收到错误。请帮我解决这个问题,找到下面的代码:
$.ajax({
type: "POST",
//dataType: "json",
url: "./QuizServlet",
success: function (responseText) {
alert("alert" + responseText);
var jsonData = JSON.parse(responseText);
for (var i = 0; i < jsonData.length; i++) {
var questions;
choice = jsonData[i].options;
ch = choice.split(",");
console.log(ch);
questions = [{ question: questionnn, choices: ch, correctAnswer: answer }];
}
}
});
同样,从数据库中获取多行时出现问题。
我添加了servlet代码,从哪里撤回json输出。
List<QuizDto> quiz=new ArrayList<QuizDto>();
quiz=QuizDao.quizdetails();
JSONArray jsonarray= new JSONArray();
for(int i=0;i<quiz.size();i++)
{
JSONObject obj = new JSONObject();
//obj.put("issueno", quiz.get(i).getIssueno());
obj.put("questions",quiz.get(i).getQuestions());
obj.put("answers",quiz.get(i).getAnswers());
obj.put("options", quiz.get(i).getOptions());
jsonarray.put(obj);
System.out.println("Json in Servelt"+ jsonarray.toString());
response.getWriter().print(jsonarray);
}
我在sysout中打印输出,它正确返回2个唯一身份记录。
Json in Servelt[{"answers":1,"questions":"what is correct answer","options":"first,second,third,fourth,"},{"answers":2,"questions":"what is quiz","options":"quiz,output,answer,question"}]
但是,在javascript中,ResponseText显示重复两次的1行,如下所示:
alert[{"answers":1,"questions":"what is correct answer","options":"first,second,third,fourth,"}][{"answers":1,"questions":"what is correct answer","options":"first,second,third,fourth,"},{"answers":2,"questions":"what is quiz","options":"quiz,output,answer,question"}]
无法理解为什么会发生这种情况
答案 0 :(得分:3)
您返回的回复可能不是JSON格式。 最常见的问题是不在对象键中添加引号。
根据您发送的数据,您实际上发送了多个连接的JSON(多个数组未封装且未用逗号分隔)。
现在应该是[[...],[...],[...]]
而不是[...][...][...]
。