Javascript jQuery结束括号错误

时间:2014-08-21 22:48:28

标签: javascript jquery ajax

我希望我的输出顺序如下:

console.log("1st 1:", y1, y2, y3, y4);
console.log("1st 2:", y1, y2, y3, y4);
console.log("2nd 1:", y1, y2, y3, y4);
console.log("2nd 2:", y1, y2, y3, y4);
console.log("3rd:", y1, y2, y3, y4);

但我在Uncaught TypeError: undefined is not a function声明中收到done

只能看到:

1st 1: 5 5 5 5
1st 2: 8 30 236 365

我发现此代码没有任何问题:

    data: (
        function() {

            // Test
            y1 = 5,
            y2 = 5,
            y3 = 5,
            y4 = 5;

            // Ajax is asynchronous
            function doRun() {
                $.ajax({
                    type: "GET",
                    url: "/getTest",
                    success: function(data) {
                        console.log("1st 1:", y1, y2, y3, y4);
                        y1 = data.V1;
                        y2 = data.V2;
                        y3 = data.V3;
                        y4 = data.V4;
                        console.log("1st 2:", y1, y2, y3, y4);
                    }
                });
                return doRun;
            };

            doRun().done(function() {
                console.log("2nd 1", y1, y2, y3, y4);
            }).fail(function() {
                console.log("2nd 2");
            });

            var data = [],
                time = (new Date()).getTime(),
                i;
            for (i = -10; i <= 0; i++) {
                console.log("3rd:", y1, y2, y3, y4);
                data.push({
                    x: time + i * 10,
                    y: 0
                });
            }
            return data;
        }()
    )

我应该怎么做才能解决这个问题并按顺序打印所有内容?

2 个答案:

答案 0 :(得分:2)

function doRun() {
                return $.ajax({
                    type: "GET",
                    url: "/getTest",
                    success: function(data) {
                        console.log("1st 1:", y1, y2, y3, y4);
                        y1 = data.V1;
                        y2 = data.V2;
                        y3 = data.V3;
                        y4 = data.V4;
                        console.log("1st 2:", y1, y2, y3, y4);
                    }
                });
            };

你回错了。您返回doRun - 与调用的函数相同。 doRun没有done属性。您打算从$.ajax返回承诺。

答案 1 :(得分:0)

您对doRun()的调用是返回doRun函数对象。这实际上是否定义了done()方法?我猜不是。