【发布时间】:2010-11-22 19:15:36
【问题描述】:
我正在尝试在 Javascript 中循环一个名为 special_ads 的 Django 数组。这个想法是我可以创建 Javascript advert 对象并将它们存储在 Javascript 数组中。 这些对象用于选择某个广告并显示附加信息。
<script type="text/javascript">
ADS = new slideshow();
{% for ad in special_ads %}
ADS.add_ad(new advert(
"{{ ad.image }}",
"Drie halen twee betalen",
"{{ ad.company.name }}",
"{{ ad.description }}",
"{{ MEDIA_URL }}{{ ad.image }}",
"{% thumbnail ad.image 55x55 crop %}",
"brown",
"white"
));
{% endfor %}
</script>
//==================================================
// ad object
//==================================================
function advert(id,title,company,description,normal_image_src,thumb_image_src,background_color,text_color) {
this.id = id;
this.title = title;
this.company = company;
this.description = description;
this.normal_image_src = normal_image_src;
this.thumb_image_src = thumb_image_src;
this.background_color = background_color;
this.text_color = text_color;
}
我不能真正使用 JSON 列表,因为在页面加载时我还需要在 html 中使用相同的数组,如下所示。
{% for ad in special_ads %}
<dd>
<a id="std_ad_{{ i }}" class="img">
<img id="{{ ad.image }}" class="enlarge" src="{% thumbnail ad.image 55x55 crop %}" alt="{{ ad.company.name }}" onclick="ADS.display(this)"/>
</a>
</dd>
{% endfor %}
问题是这不能正常工作。页面加载正确,但 广告 未添加到数组中。此外,Django 部分似乎执行正确。页面源结果如下。
<script type="text/javascript">
ADS = new slideshow();
ADS.add_ad(new advert(
"ads/logo_copy.jpg",
"Drie halen twee betalen",
"Directdoen.nl",
"DirectDoen helpt u graag met schoonmaken, tuinonderhoud en klussen. Bij DirectDoen bent u voor hulp in en om uw huis aan",
"http://127.0.0.1:8000/media/ads/logo_copy.jpg",
"",
"brown",
"white"
));
ADS.add_ad(new advert(
"ads/Untitled-1.jpg",
"Drie halen twee betalen",
"Jouwstraat.nl",
"Jouwstraat.nl is een website waar buren & straatgenoten met elkaar in contact kunnen
komen en blijven. Kijk dus snel op .
",
"http://127.0.0.1:8000/media/ads/Untitled-1.jpg",
"",
"brown",
"white"
));
ADS.add_ad(new advert(
"ads/AD.JPG",
"Drie halen twee betalen",
"Code 06",
"DirectDoen helpt u graag met schoonmaken, tuinonderhoud en klussen. Bij DirectDoen bent u voor hulp in en om uw huis aan
",
"http://127.0.0.1:8000/media/ads/AD.JPG",
"http://127.0.0.1:8000/media/ads/AD_JPG_55x55_crop_q95.jpg",
"brown",
"white"
));
</script>
我已经搜索了很多,但我找不到一个很好的教程来说明如何做到这一点。有没有人知道实现我的目标的最佳方式是什么?
【问题讨论】:
-
为什么不想使用 JSON?如果您需要在页面的其他地方按原样使用现有的数组,只需将数组的一个版本制作为 JSON。
-
我已经尝试过使用 JSON,但它并没有真正按照我需要的方式工作。也许确实有可能,但我不是 Django 和 JSON 方面的专家;)。我现在按原样工作。
标签: javascript django