我对js很新。我喜欢用jquery进行api调用。我使用URL从openweatherapi获取天气数据。
我使用以下功能进行ajax调用:
myAjaxReq(){
var o = {url: "", datatype: "" };
o.url = this.url;
o.datatype = this.datatype;
return $.ajax(o);
}
现在,当我尝试使用以下代码时,我得到了结果:
myAjaxReq().done(function(jsnData) {
$("#c3").html(jsnData.name);
}).fail(function() {
$("#c3").html("Something went wrong, please check the api request");
});
但是我做了类似下面的事情,我收到的错误是"无法读取属性'已完成'未定义"
var my_api_calls = {
weather: function() {
myAjaxReq().then(function(jsndata) {
return jsndata.name;
});
}
};
my_api_calls.weather().done(function(weather) {
$("#c3").append(weather);
});
我已经调查了link1来编写上面的代码但是没有用。我还提到了关于类似link2的问题的stacoverflow问题,但是无法理解。
请指导我如何解决,问题是什么。另外我想我正在使用jquery deffered对象,而不是promises。他们之间有什么区别。
答案 0 :(得分:0)
您的功能“天气”不会返回任何内容。看看
weather: function() {
myAjaxReq().then(function(jsndata) {
return jsndata.name;
});
}
这里的回报是有希望的。这是完全不同的东西。也许你想在函数天气和链回调中返回myAjaxReq()?