0

我有这个 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;
    }

在客户端我有这个功能,在警报声明中它给了我异常“无效字符”。

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(); 
    }
4

1 回答 1

1

您的服务器端代码在每个“对象文字”之后添加一个逗号,即使是最后一个也不应该以逗号结尾。JSON.parse()在客户端解析字符串时,这个额外的逗号会导致错误

+ "\", \"id\":" + townid + "},";
-----------------------------^ 
于 2013-02-23T15:39:41.030 回答