使用JQuery调用Google Places API时Eclipse与Chrome转义字符冲突求助
解决jQuery调用Google Places API时Chrome与Eclipse的冲突问题
Hey there, let's break down your problem and fix it step by step! The core issue here is a clash between XML syntax rules in Eclipse and valid URL formatting for Chrome, plus a small mistake in handling the API response.
为什么会出现矛盾?
- Eclipse的SAXParseException:如果你的代码是写在XML格式的文件(比如JSP、XML视图)里,XML解析器会把
&当成实体引用的开头,要求它必须以;结尾(比如&)。但你转义成&就过头了——XML解析后会把&变成&,而不是正常的&,导致Chrome识别不了URL里的参数分隔符,触发语法错误。 - 跨域与JSONP的用法:你用JSONP规避跨域是对的,但手动拼接URL参数很容易踩转义的坑,而且你还错误地用处理XML的方式去解析JSON响应。
具体解决办法
1. 用jQuery的data参数传递查询参数(避免手动拼接URL)
不要再手动把参数拼进URL里,改用jQuery Ajax的data选项来传递参数。jQuery会自动帮你处理参数的拼接和转义,既满足XML语法规则(不会在URL字符串里出现裸写的&),又能让Chrome拿到正确的URL格式。
2. 修正响应处理逻辑(JSON≠XML)
Google Places API返回的是JSON数据,不是XML,所以你之前用$(xml).find('results')的写法完全错误,应该直接操作JSON对象的属性。
修正后的完整代码
$(document).ready(function(){ $('.search_latitude').val(marker.getPosition().lat()); $('.search_longitude').val(marker.getPosition().lng()); var Lat = marker.getPosition().lat(); console.log(Lat); var Long = marker.getPosition().lng(); console.log(Long); var cafeRatings = []; $.ajax({ type: "GET", dataType: "jsonp", url: "https://maps.googleapis.com/maps/api/place/nearbysearch/json", data: { location: Lat + "," + Long, radius: 500, type: "restaurant", keyword: "cruise", key: "MY_API_KEY" // 替换成你的真实API Key }, success: function(response) { // 遍历API返回的商家数组 response.results.forEach(function(place) { // 检查商家是否有评分字段,避免undefined if (place.rating) { cafeRatings.push(place.rating); } }); alert(cafeRatings.join("\n")); }, error: function(xhr, status, error) { // 新增错误回调,方便调试请求失败的情况 console.error("请求出错啦:", status, error); } }); });
额外注意事项
- 确保你在Google Cloud Console里已经启用了Places API,并且API Key没有被限制在错误的域名下(本地开发要允许
localhost的请求)。 - jQuery的
dataType: "jsonp"会自动添加callback参数到请求中,Google Places API支持这种JSONP回调,完美解决跨域问题。
内容的提问来源于stack exchange,提问作者user9269133
相关产品推荐
相关产品推荐

