语法错误JSON.parse ajax.responsetext(Spring,jquery,ajax,gson)(Syntax Error JSON.parse ajax.responsetext (Spring,jquery,ajax,gson))
我使用Netbeans&spring framework4.0.1,没有注释只有普通的模型和视图
当我尝试发送JSON到jsp页面并使用ajax函数回调时,我无法解析响应文本,并给我出现此错误“SyntaxError:JSON.parse:JSON数据的第12行第1列出现意外字符”这是控制器代码
public ModelAndView contentlistObjective(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception { ModelAndView mv = new ModelAndView("createsettings"); List<Content> contents = new ArrayList<>(); // JSONObject obj = new JSONObject(); try { DriverManagerDataSource dataSource; dataSource = (DriverManagerDataSource)this.getBean("dataSource",hsr.getServletContext()); this.cn = dataSource.getConnection(); Statement st = this.cn.createStatement(); String objectiveid = null; objectiveid = hsr.getParameter("seleccion3"); ResultSet rs1 = st.executeQuery("SELECT name,id FROM public.content where public.content.id IN (select public.objective_content.content_id from public.objective_content where public.objective_content.objective_id = "+objectiveid+")"); while (rs1.next()) { Content eq = new Content(); contents.add(eq); // obj.put("name", rs1.getString("name")); } } catch (SQLException ex) { System.out.println("Error leyendo contents: " + ex); } Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(contents); hsr1.setContentType("application/json"); // System.out.print(json); // json = json.replaceAll("\n", ""); // json = json.trim(); // json = json.substring(1,json.length()-1); // json = json.replace("\\",""); mv.addObject(json); return mv; }
当我调试我正在返回的JSON有这个值[{“name”:“newspaper”},{“name”:“novel”}]下面是JSP代码
function comboSelectionObjective() { if (window.XMLHttpRequest) //mozilla { ajax = new XMLHttpRequest(); //No Internet explorer } else { ajax = new ActiveXObject("Microsoft.XMLHTTP"); } ajax.onreadystatechange = funcionCallBackContent; var seleccion3 = document.getElementById("objective").value; ajax.open("GET", "createsetting.htm?select=contentlistObjective&seleccion3=" + seleccion3, true); ajax.send(""); } function funcionCallBackContent() { if (ajax.readyState === 4) { if (ajax.status===200){ var data =JSON.parse(ajax.responseText); console.log(data); }
我使用的是gson库,我之前使用Json简单,但它给了完全相同的错误,我也试图替换所有的转义字符,并没有工作
是不是使用注释的问题?
感谢你的帮助
I am using Netbeans & spring framework4.0.1,without annotation only normal model&view
When i try to send a JSON to the jsp page & using ajax function call back , i am unable to parse the response text, gives me this error "SyntaxError: JSON.parse: unexpected character at line 12 column 1 of the JSON data" This is the controller code
public ModelAndView contentlistObjective(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception { ModelAndView mv = new ModelAndView("createsettings"); List<Content> contents = new ArrayList<>(); // JSONObject obj = new JSONObject(); try { DriverManagerDataSource dataSource; dataSource = (DriverManagerDataSource)this.getBean("dataSource",hsr.getServletContext()); this.cn = dataSource.getConnection(); Statement st = this.cn.createStatement(); String objectiveid = null; objectiveid = hsr.getParameter("seleccion3"); ResultSet rs1 = st.executeQuery("SELECT name,id FROM public.content where public.content.id IN (select public.objective_content.content_id from public.objective_content where public.objective_content.objective_id = "+objectiveid+")"); while (rs1.next()) { Content eq = new Content(); contents.add(eq); // obj.put("name", rs1.getString("name")); } } catch (SQLException ex) { System.out.println("Error leyendo contents: " + ex); } Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(contents); hsr1.setContentType("application/json"); // System.out.print(json); // json = json.replaceAll("\n", ""); // json = json.trim(); // json = json.substring(1,json.length()-1); // json = json.replace("\\",""); mv.addObject(json); return mv; }
When i debug json that i am returning has this value [ { "name": "newspaper" }, { "name": "novel" } ] Below is the JSP code
function comboSelectionObjective() { if (window.XMLHttpRequest) //mozilla { ajax = new XMLHttpRequest(); //No Internet explorer } else { ajax = new ActiveXObject("Microsoft.XMLHTTP"); } ajax.onreadystatechange = funcionCallBackContent; var seleccion3 = document.getElementById("objective").value; ajax.open("GET", "createsetting.htm?select=contentlistObjective&seleccion3=" + seleccion3, true); ajax.send(""); } function funcionCallBackContent() { if (ajax.readyState === 4) { if (ajax.status===200){ var data =JSON.parse(ajax.responseText); console.log(data); }
i am using gson library, i used before it Json simple but it gave exactly the same error also i tried to replace all escape characters and did not work either
Is the problem that i am not using annotations?
Appreciate your help
原文:https://stackoverflow.com/questions/43093916
最满意答案
假设你想要实际上是pythonic(或者真的,只是没有足够的疯狂来制作100个变量),你可以制作一个
list
。obj = [] for i in range(100): name=input('Your name:') obj.append(Person(name))
如果你想在循环之前设置列表的大小,以便你可以用
i
访问它,你可以做这样的事情obj = [None] * 100 for i in range(100): name=input('Your name:') obj[i] = Person(name)
Assuming you want to actually be pythonic (or really, just not insane enough to make 100 variables), you could make a
list
.obj = [] for i in range(100): name=input('Your name:') obj.append(Person(name))
If you want to set the size of your list before your loop so you can access it with
i
, you can do something like thisobj = [None] * 100 for i in range(100): name=input('Your name:') obj[i] = Person(name)
相关问答
更多-
双重迭代[重复](Double Iteration [duplicate])[2024-03-29]
使用zip() : for elem1, elem2 in zip(list1, list2): 如果其中一个列表比另一个列表长,则不会看到超出较短列表长度的元素。 在python 2上, zip()导致两个列表压缩在一起的副本,以及可能是内存负担的大型列表。 对这些较大的列表使用itertools.izip() ,它会返回一个迭代器。 在python 3上, zip()本身已经返回一个迭代器。 如果您需要循环遍历最长列表(并为缺少的较短列表元素填写填充值),请使用itertools.izip_longe ... -
当您输入Y
,输入缓冲区中有2个字符: Y和\n 。 由于answer是char[2]并且fgets总是写一个C-String,因此保存在answer的字符串将为"Y" 。 换行符保留在输入缓冲区中,因此下一个fgets将读取输入缓冲区的剩余部分。 因为它是换行符, fgets只读取换行符,因此word将包含字符串"\n" 。 您可以使用更大的维度(至少3)声明数组answer ,或者使用word代替。 如果你选择前者,那么你应该这样做 char answer[10]; ... if (str ... -
使用此模块的一种简单方法是使用time.time()来标记代码的开头,并再次使用time.time()来标记它的结尾。 之后,减去它们以便获得持续时间。 所以你的代码应该像: for times in range(50): start = time.time() #do some stuff stop = time.time() duration = stop-start print(duration) 例: >>> for i in range(3): ...
-
假设你想要实际上是pythonic(或者真的,只是没有足够的疯狂来制作100个变量),你可以制作一个list 。 obj = [] for i in range(100): name=input('Your name:') obj.append(Person(name)) 如果你想在循环之前设置列表的大小,以便你可以用i访问它,你可以做这样的事情 obj = [None] * 100 for i in range(100): name=input('Your name:') ...
-
Python迭代(Python iteration)[2021-09-19]
你需要先设置char2 = 0 for p in range(255): 实际上,你不需要计数器 - char,char2 以下将从0到ff工作 for x in range(256): for p in range(256): print chr(x).encode("hex"),chr(p).encode("hex") You need to set char2 = 0 before for p in range(255): And actually, you don't ... -
为什么关键字搜索比通过python字典进行迭代更快[复制](Why is key search faster than iteration through python dictionary [duplicate])[2022-08-15]
因为Python中的字典是使用散列表实现的。 想象一下类似于关系数据库中的索引,这使得关键的查找操作更快。 参考 Because dictionaries in python are implemented using hash tables. Think something similar to indices in a relational database, which make key seeking operations faster. Reference -
在python中的迭代语句之后是否存在迭代变量?(Do iteration variable exist after the iteration statement in python? [duplicate])[2022-01-15]
是的,循环结束时不会删除迭代变量。 正如文档所说 :“循环结束时不会删除目标列表中的名称”。 这与变量范围有关。 正如已经指出的那样,变量i存在于你所在函数的范围内。循环不会在python中创建额外的作用域。 Yes, your iteration variable isn’t deleted when the loop is finished. As the documentation puts it: „Names in the target list are not deleted when the ... -
在连接之前,必须将int转换为字符串。 你必须使用 print("The length of " + word + " is " + str(len(word))) 字符串格式也可以用作, print("The length of %s is %d"%(word,len(word))) 这里, %s用于字符串 %d用于int You have to convert the int to string before you concatenate. You have to use print("The l ...
-
在迭代过程中打印当前值和下一个值[复制](Print current value and next value during iteration in Python [duplicate])[2023-10-12]
我找到的最简单的方法是: a = ['a','b','c','d','e'] for i,nexti in zip(a,a[1::]): print i,nexti The easiest way I found was: a = ['a','b','c','d','e'] for i,nexti in zip(a,a[1::]): print i,nexti -
您可以在列表中使用iterator 。 有了这个,你可以在循环时改变循环项目: it = iter(list1) for i in it: if i == 5: next(it) # Does nothing, skips next item else: #do something 如果你打算使用i==5的值,你应该在评估条件之前do something : it = iter(list1) for i in it: #do something ...