ajax - ajax调用返回值问题
问题描述
我在使用 ajax 调用时遇到问题,我认为返回值没有正确返回。
我有一个加载 2 个 javascript 文件的 index.html 页面:
- index.js :用于 index.html 上的动态 GUI 内容
- application.js :进行 ajax 调用(使用 Javascript 模块模式)
index.js
$(document).ready(function() {
console.log(ApplicationModule.getEventById(123)); // undefined if I use return result[0];
})
应用程序.js
var ApplicationModule = (function () {
// return "foo"; this works in index.html ("foo")
function getEventById(id) {
// ajax call returns a json object (list of {"title":"<the title>"} objects)
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
url: "/api/v1/eventtool/" + id,
success: function (result) {
console.log(result[0]); // works fine -> {"title":"my title"}
return result[0]; // does not work in index.html (undefined)
}
});
}
return {
getEventById : getEventById
};
})(ApplicationModule || {});
如果我取消注释 [ return "foo" ] 行,一切都会按预期工作,并且我会在控制台上看到 "foo"。如果我评论这一行以执行 ajax 调用,我会得到“未定义”。为什么?
我的ajax调用有问题吗?
解决方案
返回值不起作用,您应该使用 DOM 指定一个元素,如下所示:$("#el").html(result[0]);
推荐阅读
- excel-formula - 仅用于未来期间的两个日期之间按月计算天数的公式
- javascript - 尝试使用 XMLHttpsrequest 获取 Imgur 的访问令牌
- python - 有没有比 pickle 或常规 Python 文件更快的方法来存储大字典?
- user-interface - Walk GUI Toolkit for GO 中的 Filechooser 组件
- java - 如果连接到外部 Midi 输出设备,Java 定序器会延迟循环
- javascript - Moment.js:查找今天有人评论的帖子
- angular - ../node_modules/@ng-bootstrap/ng-bootstrap/accordion/accordion.d.ts(1,75) 中的错误:错误 TS2307:找不到模块“@angular/core”
- macos - 哪些版本的 Vagrant 和 VirtualBox 在 MacOS 上兼容
- firebase - 在 Firestore 中忽略 Nil 值的最佳实践
- python - QuantLib-Python 中的现金结算掉期期权定价