gpt4 book ai didi

javascript - 将值从代码隐藏传递给 js

转载 作者:行者123 更新时间:2023-11-30 20:05:19 24 4
gpt4 key购买 nike

我有这个在 map 上显示对象的 javascript 代码:

 <script type="text/javascript">
google.maps.event.addDomListener(window, 'load', init);

function init() {
var locations = [
[40.6128, -73.9976, "images/pin-apartment.png", "estate-details-right-sidebar.html", "images/infobox-offer1.jpg", "Fort Collins, Colorado 80523, USA", "$320 000"],[41.6926, -87.6021, "images/pin-house.png", "estate-details-right-sidebar.html", "images/infobox-offer5.jpg", "E. Elwood St. Phoenix, AZ 85034, USA", "$300 000"]
];

offersMapInit("offers-map", locations);
}

</script>

但我希望它从数据库/c# 中填充。我怎样才能做到这一点?

我怎样才能将这种数组从我的 page_load 传递到这个 js 脚本?

 protected void Page_Load(object sender, EventArgs e){}

最佳答案

您可以使用 JsonConvert.SerializeObject 序列化 C# 数组。例如

protected string StringArray { get; set;}
Page_Load(object sender, EventArgs e) {
StringArray = JsonConvert.SerializeObject(new string[] {"foo", "bar"});
}

在 Javascript 中:

<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', init);

function init() {
var locations = <%= StringArray %>;

offersMapInit("offers-map", locations);
}

</script>

您还可以从 C# 声明变量:

var stringArray = JsonConvert.SerializeObject(new string[] {"foo", "bar"});
ClientScript.RegisterStartupScript(GetType(), "locations", $"var locations = {stringArray};", true);

关于javascript - 将值从代码隐藏传递给 js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52995379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com