为什么这段代码给了我一个例外无效字符

时间:2013-02-23 15:10:57

标签: javascript json

我有这个Web服务,它获取城市的所有名称并返回json格式的字符串。

public  String  getDataForTowns( ) throws ClassNotFoundException 
{   
   String  strXml = "";

        Class.forName("org.postgresql.Driver");

            try 
            {
                conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/plovdivbizloca", "postgres", "tan");
            }   

        catch (SQLException ex) {
            ex.printStackTrace();
        }

        Statement mystmt = null;
        String selectQuery = "select * from municipality_id";
        try {
            mystmt = conn.createStatement();
            ResultSet mysr = mystmt.executeQuery(selectQuery);

            ResultSetMetaData rsmd = mysr.getMetaData();
            int colCount = rsmd.getColumnCount();
            int numberrow = 0;

            strXml += "{\"rows\": [";
            while (mysr.next()) 
            {               
                    String townname = mysr.getString(2);
                    String townid=mysr.getString(1);

                    strXml += "{\"town\":\"" + townname
                            + "\", \"id\":" + townid + "},";


                //strXml += ",";
            }
            strXml += "]}";
        } 

        catch (Exception ex) 
        {
        }

        return strXml;
    }

并且在客户端我已经有了这个功能,并且在alert语句中它给了我异常“无效字符”。

function loadTownSelect()
    {
         select =  document.getElementById('sphSel');
         createXMLHttpRequest();

         var txtDrop = new Array();
         var idDrop= new Array();

         xmlhttp.onreadystatechange = function() 
        { 
            if (xmlhttp.readyState==4 && xmlhttp.status==200) 
            {
                alert(xmlhttp.responseText);
                var xmlObj = xmlhttp.responseXML;   

                var textXML = xmlObj.documentElement.firstChild.firstChild.nodeValue;
                alert(textXML);

                var nwresp = JSON.parse(textXML);
                alert (nwresp.rows[2].town);               
            }
        }

        var url = "http://localhost:9091/localbusscat/services/localbusscat/getDataForTowns";
        xmlhttp.open("GET", url, true);
        xmlhttp.send(); 
    }

1 个答案:

答案 0 :(得分:1)

您的服务器端代码在每个“对象文字”之后添加逗号,即使是最后一个也不应以逗号结尾。在客户端

上使用JSON.parse()解析字符串时,这个额外的逗号会导致错误
+ "\", \"id\":" + townid + "},";
-----------------------------^