ajax调用返回值的问题

ajax调用返回值的问题,ajax,Ajax,我对ajax调用有问题,我认为返回值没有正确返回 我有一个index.html页面,可加载2个javascript文件: index.js:用于index.html上的动态GUI内容 application.js:进行ajax调用(使用Javascript模块模式) index.js application.js var ApplicationModule=(函数(){ //返回“foo”;它在index.html(“foo”)中工作 函数getEventById(id){ //ajax调用

我对ajax调用有问题,我认为返回值没有正确返回

我有一个index.html页面,可加载2个javascript文件:

  • index.js:用于index.html上的动态GUI内容
  • application.js:进行ajax调用(使用Javascript模块模式)
index.js application.js
var ApplicationModule=(函数(){
//返回“foo”;它在index.html(“foo”)中工作
函数getEventById(id){
//ajax调用返回一个json对象(包含{“title”:“}个对象的列表)
$.ajax({
键入:“获取”,
contentType:“应用程序/json;字符集=utf-8”,
数据类型:“json”,
async:true,
cache:false,
url:“/api/v1/eventtool/”+id,
成功:功能(结果){
console.log(结果[0]);//工作正常->{“标题”:“我的标题”}
返回结果[0];//在index.html中不起作用(未定义)
}
});
}
返回{
getEventById:getEventById
};
})(应用模块| |{});
如果我取消对行[return“foo”]的注释,一切都会按预期进行,我会在控制台上看到“foo”。 如果我注释这一行以执行ajax调用,我会得到“未定义”。为什么?


我的ajax调用有问题吗?

返回值不起作用,应该用DOM指定一个元素,如下所示:
$(“#el”).html(结果[0])

我使用fetch和promises的最终解决方案:

application.js

function getEventById(id) {
    return fetch(myurl)
        .then(function(response) {
            return response.json();
        })
        .then(function(myJson) {                
            return myJson[0];
        });
}
index.html

const check_event = ApplicationModule.getEventById(123);
// console.log(check_event); // Promise {<pending>}
// [[PromiseStatus]] "resolved"
// [[PromiseValue]]  {"title":"my title"}
check_event.then(function(data) {
    console.log(JSON.stringify(data)); // {"title":"my title"}
});
const check\u event=ApplicationModule.getEventById(123);
//console.log(检查事件);//承诺{}
//[[PromiseStatus]]“已解决”
//[[PromiseValue]]{“头衔”:“我的头衔”}
检查事件。然后(函数(数据){
console.log(JSON.stringify(data));//{“标题”:“我的标题”}
});

但是我需要在其他页面(在其他.js文件中)多次调用这个getEventById()函数,所以我想返回一个可以在其他.js文件中使用的对象。在这种情况下,您可以在html元素上调用该函数,并将其id传递给该函数,在该函数中,您可以对该元素执行任何操作,如下所示:
onclick=“getEventByID(ID)”
。现在函数中有了元素id。嗯……然后我必须重新考虑我的应用程序设计,因为我不想用这个ajax调用修改dom,而是返回一个我可以访问其属性的对象。当然,我希望它有用,如果是,检查向上箭头键,以便其他用户可以正确地使用您的问题。并且没有一种方法可以从ajax调用返回某些内容,以便可以重复使用?
function getEventById(id) {
    return fetch(myurl)
        .then(function(response) {
            return response.json();
        })
        .then(function(myJson) {                
            return myJson[0];
        });
}
const check_event = ApplicationModule.getEventById(123);
// console.log(check_event); // Promise {<pending>}
// [[PromiseStatus]] "resolved"
// [[PromiseValue]]  {"title":"my title"}
check_event.then(function(data) {
    console.log(JSON.stringify(data)); // {"title":"my title"}
});