我有一个数据表,每行我需要执行一个javascript函数(相同的javascript函数,但具有不同的值)。
对于每一行,它执行了一个javascript函数,并将结果返回给后面的代码(trought web method)。
但是,使用我的实际代码,它只执行一次(表的第一行)。
我有这个: C#
string strScript = "";
foreach (DataRow row in dtLodgings.Rows)
{
strScript = strScript + "\n" + "GetInfoGMaps('" + row["Name"].ToString() + "'," + row["Latitude"].ToString().Replace(",", ".") + "," + row["Longitude"].ToString().Replace(",", ".")+ ");";
}
strScript = strScript.Replace("'", "\'");
ClientScript.RegisterStartupScript(GetType(), "GetInfoGMaps", strScript, true);
javascript
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
var map, service;
function GetInfoGMaps(name, latitude, longitude) {
var loc= null;
if (latitude != "" && longitude != "") {
loc = new google.maps.LatLng(latitude, longitude);
}
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: loc,
zoom: 15
});
service = new google.maps.places.PlacesService(map);
var request = {location: loc, radius: 50000, keyword: name};
service.radarSearch(request, callback); // i got the data and i sent to c# trought ajax
}
C#
[WebMethod]
public static void GetInfoGMaps(InfoMaps lodg)
{
if (lodg != null)
{
// the data is saved in database
}
}
我试图在控制台(chrome web browser)中执行strString,但我发现 undefined ,我不明白为什么。似乎当我运行radarSearch函数时会给出undefined。
GetInfoGMaps('Mak Albania Resort Durres',41.2314605712891,19.5132293701172);
GetInfoGMaps('Mak Albania Resort Durres',41.2314605712891,19.5132293701172);
GetInfoGMaps('Mak Albania Resort Durres',41.2314605712891,19.5132293701172);
任何人都可以帮助我?
由于
答案 0 :(得分:2)
根据documentation,每个启动脚本由其键及其类型唯一标识。具有相同密钥和类型的脚本被视为重复。像这样为每个键添加唯一值..
int i = 0;
foreach (DataRow row in dtTable.Rows) {
ClientScript.RegisterStartupScript(GetType(), "GetInfoGMaps" + i, "GetInfoGMaps('" + row["Name"].ToString() + "'," + row["Latitude"].ToString().Replace(",", ".") + "," + row["Longitude"].ToString().Replace(",", ".")");", true);
i++;
}
答案 1 :(得分:0)
ClientScript应该在foreach循环之外,因为您注册 GetInfoGMaps N行次。
foreach首先创建脚本字符串。
'
字符以避免破坏您的javascript 示例:
string strScript = "";
foreach (DataRow row in dtTable.Rows) {
strScript = strScript + "\n" + "GetInfoGMaps('" + row["Name"].ToString() + "'," + row["Latitude"].ToString().Replace(",", ".") + "," + row["Longitude"].ToString().Replace(",", ".")");";
}
//clean/escape ' char to avoid breaking your script
clientScript = clientScript.Replace("'", "\'")
// now it may be ok :
ClientScript.RegisterStartupScript(GetType(), "GetInfoGMaps", clientScript, true);