首页 > 解决方案 > 无法在 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)

不过我真的很困惑。为什么它无法读取完成的属性?

标签: javascriptjqueryajax

解决方案


您必须将您的函数调用到 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
}

推荐阅读