注意:出于隐私目的,我屏蔽了数据。
我有 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>
使用实际详细信息运行上述代码后,我在浏览器控制台上看不到任何代码错误。但另外,我无法在页面上看到广告。我错过了什么吗?
我试过在浏览器中调试我没有收到任何错误。