javascript - 无法在 AJAX json 承诺中读取 done 的属性
问题描述
我正在尝试学习如何做 javascript 承诺。我的目标是让一个按钮运行一个函数,该函数显示另一个函数的承诺结果。这是我与教程的距离:
function myfunction() {
var post = ajaxrequest();
post.done(function (r) {
console.log(r);
});
}
function ajaxrequest() {
console.log("hello");
$.ajax({
url: "https://jsonplaceholder.typicode.com/todos/1",
dataType: 'json',
data: {
},
});
};
我得到的错误是:
Uncaught TypeError: Cannot read property 'done' of undefined
at myfunction (indexboll.html:11)
at HTMLInputElement.onclick (indexboll.html:6)
不过我真的很困惑。为什么它无法读取完成的属性?
解决方案
您必须将您的函数调用到 Ajax 调用的成功回调函数中,如下所示。让我知道您还有更多问题。
function myfunction(r) {
console.log(r);
}
function ajaxrequest() {
console.log("hello");
$.ajax({
url: "https://jsonplaceholder.typicode.com/todos/1",
dataType: 'json',
data: {},
success: function(response){
//if request if made successfully then the response represent the data
myfunction(response);
}
});
};
ajaxrequest();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
输出:
hello
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
推荐阅读
- python - 如何使用 exec() 调用预定义代码?
- c# - 解析 JSON 结果并检查状态中的指定字符串
- javascript - Url 更改但不渲染组件 React Router
- java - 如何创建使用 Scanner 类来注册用户输入的方法?
- python - Celery 上的 Heroku 应用程序错误:raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
- python-asyncio - 从模块外部的异步动态更改日志级别
- javascript - React 基本 api 调用问题
- android - onSaveInstanceState() 在华为 P20 (EMUI 10) 上的进程死亡后不起作用
- html - 为什么我的 flexbox 没有占据它所在容器的整个高度?
- pandas - pandas df.to_parquet 写入多个较小的文件