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