将xmlhttp.response文本转换为json并打印(详细解释错误)?

时间:2018-04-19 12:31:49

标签: javascript json ajax jsp

在下面的代码中,我想将我的xmlhttp.responseText转换为JSON对象并将其打印到html元素名称“deta” 在运行下面的代码我得到我的数据打印在控制台但html页面没有反映。 ?

我使用xmlhttp.responseText将数据打印在html页面上,但在将其转换为json后会抛出错误

以下错误

  

未捕获的SyntaxError:位置12的JSON中出现意外的标记R.           在JSON.parse()
          在XMLHttpRequest.xmlhttp.onreadystatechange((index):112)

JS:

function myFunction() {


  var name = document.getElementById("ab").value;

  var urls = "time.jsp?name=" + name;

  var xmlhttp;
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
  }
  // code for IE6, IE5
  else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }

  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

      var a = JSON.parse(xmlhttp.responseText);
      document.getElementById("deta").innerHTML = a;
      // want  data be printed in "deta" html element

    }
  }

  xmlhttp.open("GET", urls, true);
  xmlhttp.send();
}

HTML

<input type="text" id="ab" name="search" placeholder="Search.." onkeyup="myFunction()">   

JSP

JSP code --------------------------------------------

<%@page import="java.sql.DriverManager"%>
    <%@page import="java.sql.ResultSet"%>
    <%@page import="java.sql.PreparedStatement"%>
    <%@page import="java.sql.Connection"%>
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%
        try
    {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
            PreparedStatement ps = con.prepareStatement("SELECT  * FROM student WHERE  name = ?"); 
                String name=request.getParameter("name");
                ps.setString(1, name);
                ResultSet res = ps.executeQuery();

              ResultSetMetaData rsmd = res.getMetaData();
              int columnsNumber = rsmd.getColumnCount();

               if(res.first())
                {

                     String str= res.getString(1)+"  "+res.getString(2)+"  "+res.getString(3)+"  "+res.getString(4)+"  "+res.getString(5);  
                    out.print(str) ;

                }else
                {

                    out.print("Name not valid");
                }
                con.close();

    } catch (Exception e){
                System.out.println(e);  
            }
    finally
    {

    }
    %>

0 个答案:

没有答案