简体   繁体   English

当ajax调用完成时,如何确保代码运行?

[英]How to ensure that code is run when when ajax call is finished?

I'm used to writing ruby where I get data, then I manipulate it, then I display it. 我习惯在获取数据的地方编写红宝石,然后操纵它,然后显示它。

In javascript land, I'm getting some json, on success: manipulate and display. 在javascript领域,我得到了一些成功的json:操纵和显示。

I want to separate out my code to look like this 我想把我的代码看起来像这样

 $("#uiElement").click(function(){
    data = getData();
    upDateUi(data);
})

function getData(){
    var fishes;
    $.ajax({
        url: '/api/fishes/'+q,
        dataType: 'json',
        success: function(data){
            return data;
            //I don't want to manipulate the ui in this code;
            //upDateUi(data)
        },
        error: function(req,error){
            console.log(error);
        }
    })
    return fishes;
}

You should probably get used to event-based programming. 您可能应该习惯于基于事件的编程。 Your code could use callbacks: 您的代码可以使用回调:

$("#uiElement").click(function(){
    getData(upDateUi); // make sure upDateUi is defined, it will be passed data
})

function getData(callback){
    var fishes;
    $.ajax({
        url: '/api/fishes/'+q,
        dataType: 'json',
        success: function(data){
            //I don't want to manipulate the ui in this code;
            //upDateUi(data)
            callback(data);
        },
        error: function(req,error){
            console.log(error);
        }
    })
    return fishes;
}

Hard to tell what your question is, but success is any function, so this: 很难说出您的问题是什么,但是success任何功能,因此:

...
success: function(data){
    upDateUi(data);
},
...

Can be equivalently written as: 可以等效地写为:

...
success: upDateUi,
...

Other than that, not sure what you mean by "I don't want to manipulate the ui in this code". 除此之外,不确定“我不想在此代码中操作ui”的含义。

Define a callback, and then in the success method invoke the callback: 定义一个回调,然后在成功方法中调用该回调:

$("#uiElement").click(function(){
    data = getData(upDateUi);
})

function getData(callback) {
    $.ajax({
        url: '/api/fishes/'+q,
        dataType: 'json',
        success: function(data){
            if (callback !== undefined) {
               callback(data);
            }
        },
        error: function(req,error){
            console.log(error);
        }
    })
}

The only way to do that is to use a synchronous fetch, which waits for the response, but its a bad idea, as no other javascript can run (and in some browsers - nothing can run) until the response is received. 唯一的方法是使用同步获取,它等待响应,但这是一个坏主意,因为在收到响应之前,其他JavaScript都无法运行(在某些浏览器中无法运行)。

If you really, really, really want it though: 但是,如果您真的,真的,真的想要它:

$("#uiElement").click(function(){
    data = getData();
    upDateUi(data);
})

function getData(){
    var fishes;
    $.ajax({
        url: '/api/fishes/'+q,
        dataType: 'json',
        async: false,
        success: function(data){
            fishes = data;
        },
        error: function(req,error){
            console.log(error);
        }
    })
    return fishes;
}

I'm not shure if is this what you want. 我不确定这是否是您想要的。

successFunction(data){
    //you can do everything here
}
errorFunction(req,error){
    console.log(error);
}
function getData(){
    var fishes;
        $.ajax({
            url: '/api/fishes/'+q,
            dataType: 'json',
            success: successFunction,
            error: errorFunction
        })
        return fishes;
    }

You can separate the logic that updates the UI from the logic that retrieves the data from the server using a callback pattern : 您可以使用callback pattern将更新UI的逻辑与从服务器检索数据的逻辑分开:

$("#uiElement").click(function(){
        var upDateUi = function(data) {
            /* ... logic ... */
        };

        getData(upDateUi);
})

function getData(callback){
    $.ajax({
        url: '/api/fishes/'+q,
        dataType: 'json',
        success: function(data){
            callback(data);
        },
        error: function(req,error){
            console.log(error);
        }
    })
}

For more information on functions and scopes: 有关功能和范围的更多信息:

https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope https://developer.mozilla.org/zh-CN/JavaScript/Reference/Functions_and_function_scope

For more information on how I defined the upDateUi function: 有关如何定义upDateUi函数的更多信息:

https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope#Recursion https://developer.mozilla.org/zh-CN/JavaScript/Reference/Functions_and_function_scope#Recursion

This code might be good for your needs: 此代码可能符合您的需求:

var myData = $.parseJSON($.ajax({
    url: "./somewhere",
    type: 'get|post',
    async: false,
    data: { what: "ever" }
}).responseText);

Then you just proceed with whatever you want to do with the results. 然后,您可以继续进行结果处理。

 $("#uiElement").click(function(){
    var myData = $.parseJSON($.ajax({
        url: "./somewhere",
        type: 'get|post',
        async: false,
        data: { what: "ever" }
    }).responseText);
    upDateUi(myData);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM