JavaScript的code执行和Ajax的异步JavaScript、code、Ajax

2023-09-10 18:33:03 作者:忘忧

我看过配发有关函数前pressions VS声明,回调,吊装,我也得到了这个最普通的想法,但我想我不能完全掌握,因为下面的code概念,让我张贴的code,然后问了真正的问题。

I have read allot about function expressions vs declaration, callbacks, hoisting, and I get the general idea of most of this but I guess I can't quite grasp the concept because of the below code, let me post the code and then ask the real questions.

    var url = "beverages.txt";


   var GridModel = function () {
        this.items = ko.observableArray();
        var me = this;
        $.ajax({
            datatype: 'json',
            url: "beverages.txt"
        }).done(function (data) {
            debugger;
            var jsonData = $.parseJSON(data);
            me.items(jsonData);
        });
    };


    var model = new GridModel();

    // prepare the data
    var source =
    {
        datatype: "observablearray",
        datafields: [
            { name: 'name' },
            { name: 'type' },
            { name: 'calories', type: 'int' },
            { name: 'totalfat' },
            { name: 'protein' },
        ],
        id: 'id',
        localdata: model.items
    };

    var dataAdapter = new $.jqx.dataAdapter(source);

    $("#grid").jqxGrid(
    {
        width: 670,
        source: dataAdapter,
        theme: 'classic',
        columns: [
          { text: 'Name', datafield: 'name', width: 250 },
          { text: 'Beverage Type', datafield: 'type', width: 250 },
          { text: 'Calories', datafield: 'calories', width: 180 },
          { text: 'Total Fat', datafield: 'totalfat', width: 120 },
          { text: 'Protein', datafield: 'protein', minwidth: 120 }
        ]
    });

    ko.applyBindings(model);
});

好了,所以这个code正常工作,它调用的VAR =新GridModel Ajax请求();问题是,如果我添加一个调试器; VAR模型=新GridModel后声明();它失败。另外Ajax请求的内部调试语句不火,但是如果我VAR模型=新GridModel后删除debugger语句();那么阿贾克斯的火灾,我可以调试该请求。为什么它与附加调试失败,是因为VAR GridModel是防爆pression。

Ok so this code works fine, it calls the ajax request by var model = new GridModel();. The problem is that if I add a debugger; statement after var model = new GridModel(); it fails. Also the debugger statements inside of the ajax request don't fire, however if I remove the debugger statement after the var model = new GridModel(); then ajax fires and I can debug the request. Why does it fail with the additional debugger, is it because var GridModel is an Expression.

基本上要我想要做的是为创建一个声明功能,我可以打电话,当Ajax请求完成后我回到了observableArray我。如果我改变这样的功能

Basically want I would like to do is is create a declaration function that I can call and when ajax request is done I return the observableArray me. If I change the function like this

  function GridModel (param1,param2) {
            this.items = ko.observableArray();
            var me = this;
            $.ajax({
                datatype: 'json',
                url: "beverages.txt"
            }).done(function (data) {
                debugger;
                var jsonData = $.parseJSON(data);
                me.items(jsonData);
            });
            return me
        };

那么我想只能够调用该函数这样的VAR myitems = GridModel(参数1,参数2)与期望myitems现在持有的Ajax请求的结果。我只是不完全了解code执行流程是如何工作的,如果有人可以解释为什么底部的功能无法正常工作,以及如何得到它的工作我会AP preciate它。

Then I would like to just be able to call that function like this var myitems = GridModel(param1,param2) with the expectation that myitems will now hold the results of the ajax request. I just don't fully understand how the code execution flow works, If someone could explain why the bottom function doesn't work and how to get it to work I would appreciate it.

谢谢, 丹

推荐答案

如果你有一个异步操作(比如Ajax请求),以及其他一切依赖于它的结果,从回调。不能使用返回语句,它仅适用于同步code。

If you have an asynchronous operation (like an Ajax request), and everything else depends on its result, resume your program's flow from the callback. You can't use return statements, it only works for synchronous code.

您可能需要修改 GridModel 构造带回调作为参数:

You may want to modify your GridModel constructor to take a callback as a parameter:

var GridModel = function (callback) {
    this.items = ko.observableArray();
    $.ajax({
        datatype: 'json',
        url: "beverages.txt"
    }).done(callback);
};

然后恢复你的程序流程从回调里面:

Then resume your program flow from inside the callback:

function resumeMyProgramFlow(data) {
    // Now you can use the data, resume flow from here
    debugger;
    var jsonData = $.parseJSON(data);
    model.items(jsonData);
    // etc.
}

和实例 GridModel 是这样的:

var model = new GridModel(resumeMyProgramFlow);