gpt4 book ai didi

javascript - 如何很好地处理ajax解析器错误?

转载 作者:行者123 更新时间:2023-11-28 06:58:18 25 4
gpt4 key购买 nike

我有一个 Google 广告项目,需要我获取多个“setTargeting('', '');”来自 json 文件上的对象数组(通过 url)--> {"country": "Netherlands", "city": "Amsterdam"}。到目前为止一切正常;但是,假设网络失败,或者请求的 JSON 解析失败等 - 我想传递一个空数组以确保该广告位仍会显示没有定位的广告。

什么是好的做法?

Advertisements.cachedCategoriesByUrl = {};

Advertisements.getCategories = function(categoriesUrl) {

var cachedCategories = Advertisements.cachedCategoriesByUrl[categoriesUrl];

if(cachedCategories){

return cachedCategories;

} else {

var getCategories = $.ajax({
url: categoriesUrl,
data: { format: 'json' },
error: function(jqXHR, status, thrownError) {
=> I'd like to pass an empty array so the slot will show
ads with no targetting set.
However this doesn't seem to be working.

Do I need to do callback?
}
});

Advertisements.cachedCategoriesByUrl[categoriesUrl] = getCategories;
return getCategories;
}
}

注意:return getCategories 在 ajax 调用完成之前运行。如何确保 return getCategories 获取我的错误更新(如果 JSON 请求失败或无效,我想传递一个空数组)。抱歉,我正在学习过程中。

最佳答案

用这个解决了它:

$.ajax({
url: ad.categoriesUrl
}).then(function(data){
Advertisements.advertisementSlot(ad, data);
}, function(data){
data = {};
Advertisements.advertisementSlot(ad, data);
});

关于javascript - 如何很好地处理ajax解析器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32376680/

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