[英]Strange character added when writing to file
I am writing the following line to the end of an html file as javascript. 我将以下行作为javascript写到html文件的末尾。 For some reason after the place variable is written to the file, a new line or some similar character is added.
由于某种原因,将place变量写入文件后,将添加新行或一些类似字符。 I wouldnt mind this because I won't be looking through the written script, but chrome is telling me its an illegal character.
我不会介意,因为我不会浏览书面脚本,但是chrome告诉我它是非法字符。
Code to write to html: 写入html的代码:
map_html.write(
"geocoder.geocode( { 'address': '" + place + "'}, function(results, status) {\n\
var marker = new google.maps.Marker();\n\
marker.setPosition(results[0].geometry.location);\n\
marker.setMap(map);\n\
bounds.extend(marker.position);\n\
});\n"
)
Output: 输出:
geocoder.geocode( { 'address': 'Brooklyn, NY
'}, function(results, status) {
var marker = new google.maps.Marker();
marker.setPosition(results[0].geometry.location);
marker.setMap(map);
bounds.extend(marker.position);
});
Replace your code with: 将代码替换为:
var geo_json = JSON.stringify({ 'address': place});
map_html.write(
"geocoder.geocode(" + geo_json + ", function(results, status) {\n\
var marker = new google.maps.Marker();\n\
marker.setPosition(results[0].geometry.location);\n\
marker.setMap(map);\n\
bounds.extend(marker.position);\n\
});\n"
)
This will sidestep the issue and will allow you to see what the stringify
ed json would look like. 这将避开该问题,并使您可以看到
stringify
ed json的外观。 It's generally a bad idea to write your own json. 编写自己的json通常不是一个好主意。 Let javascript generate json, it's good at that.
让javascript生成json,这非常有用。
If that still causes pain, then try var geo_json = JSON.stringify({ 'address': place.trim()});
如果仍然引起疼痛,请尝试
var geo_json = JSON.stringify({ 'address': place.trim()});
which will strip whitespace from the ends of the place
string. 它将从
place
字符串的末端去除空格。
If that still causes pain, then try a regex to validate the place
input. 如果仍然引起疼痛,请尝试使用正则表达式来验证
place
输入。 Something like [A-Za-z_ ,]+
像
[A-Za-z_ ,]+
EDIT 编辑
Oh, crap, I mixed up javascript and python here. 哦,废话,我在这里混合了javascript和python。
import json
geo_json = json.dumps({ 'address': place})
map_html.write(
"geocoder.geocode(" + geo_json + ", function(results, status) {\n\
var marker = new google.maps.Marker();\n\
marker.setPosition(results[0].geometry.location);\n\
marker.setMap(map);\n\
bounds.extend(marker.position);\n\
});\n"
)
How about trying a multiline string? 尝试多行字符串怎么样?
map_html.write(
"geocoder.geocode( { 'address': " + place + "}, function(results, status) {" + """
var marker = new google.maps.Marker();
marker.setPosition(results[0].geometry.location);
marker.setMap(map);
bounds.extend(marker.position);
});
"""
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.