javascript - googletag 从 API 响应动态定义槽不起作用
问题描述
注意:出于隐私目的,我屏蔽了数据。
我有 API 响应,它为我提供以下信息:此外,API 响应是动态的,因此根据业务需求,我会获得 2 或 20 个广告位信息。
{
"googletags":[
{
"networkId":"xyz",
"targetedAdUnit":"Test_Offers_1",
"adSlotCreativeSize":[
[
336,
280
],
[
320,
100
]
],
"divGPTId":"div-gpt-ad-1"
},
{
"networkId":"xyz",
"targetedAdUnit":"Test_Offers_2",
"adSlotCreativeSize":[
[
336,
280
],
[
320,
100
]
],
"divGPTId":"div-gpt-ad-2"
}
.
.
.
.
.
.
.
.
{
"networkId":"xyz",
"targetedAdUnit":"Test_Offers_n",
"adSlotCreativeSize":[
[
336,
280
],
[
320,
100
]
],
"divGPTId":"div-gpt-ad-n"
}
]
}
我正在使用此响应并在运行时定义插槽。
javascript代码:
window.googletag = window.googletag || { cmd: [] };
function googleTags(url, cFunction) {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open('GET', url, true);
xhttp.send();
}
function pushGTMtags(xhttp) {
const tags = JSON.parse(xhttp.responseText)['googletags'];
window.googletag.cmd.push(function () {
for (let i = 0; i < tags.length; i++) {
const str = `/${tags[i].networkId}/${tags[i].targetedAdUnit}`;
const adSlotCreativeSize = tags[i].adSlotCreativeSize;
const divGPTId = tags[i].divGPTId;
window.googletag
.defineSlot(
str,
adSlotCreativeSize,
divGPTId
)
.addService(window.googletag.pubads());
}
window.googletag.pubads().enableSingleRequest();
window.googletag.pubads().collapseEmptyDivs();
window.googletag.enableServices();
});
}
googleTags('apiUrl', pushGTMtags);
HTML :将此 HTML 视为使用 divGPTId 进行动态迭代。下面只是一个例子。我正在迭代基于 API response.length 的 div。
<div class="slot " id="div-gpt-ad-0">
<script>
googletag.cmd.push(function () {
googletag.display('div-gpt-ad-0');
});
</script>
</div>
使用实际详细信息运行上述代码后,我在浏览器控制台上看不到任何代码错误。但另外,我无法在页面上看到广告。我错过了什么吗?
我试过在浏览器中调试我没有收到任何错误。
解决方案
推荐阅读
- list - 如何将列表划分为随机长度的(子)列表?
- c# - 从桌面上的其他用户切换回来后,WPF UI 投射出奇怪的黑色阴影
- c++ - 如何在cmake中要求一个没有二进制文件的仅头文件库?
- html - VBA到IE上的复选框
- microsoft-graph-api - 无法在 Office365 日历中创建新文件夹
- avro - 使用 Apache Beam 写入通用记录时出现 Avro“未打开”异常
- java - 如何使用 Selenium (Java) 为具有较高 z-index 的 div 中的元素自动点击
- variables - WooCommerce:只有 1 个选项时如何自动选择变体属性下拉字段?
- json - HTTP gzip JSON 未在 Firefox 中解码
- compiler-errors - Hitech编译器编译问题