简体   繁体   English

调用函数时变得不确定

[英]Getting undefined when calling the function

I have this function which parses the JSON. 我具有解析JSON的此函数。 I am getting undefined when I am calling it in a .live function. 当我在.live函数中调用它时,我变得不确定。

Here is the function that I have created, 这是我创建的功能,

function getAbc() {
                    var details;
                    var id = $(this).attr('data-id');
                    $.ajax({
                        url : '/index.php/data',
                        type : 'GET',
                        data : 'persons[]=' + id,
                        success : function(data, textStatus, xhr) {
                            details = JSON.parse(data);
                        },
                    });
                    return details;
                }

I am simply calling like this, getAbc(). 我只是这样叫getAbc()。 And is there any way that I can access details variable in the function? 有什么方法可以访问函数中的details变量?

Use continuation passing style. 使用延续传递样式。 The $.ajax is async in nature. $.ajax本质上是异步的。

function getAbc(callback) {
    var details;
    var id = $(this).attr('data-id');
    $.ajax({
       url : '/index.php/data',
       type : 'GET',
       data : 'persons[]=' + id,
       success : function(data, textStatus, xhr) {
           details = JSON.parse(data);
           callback(details);
       }
    });
}

function getAbc(function (details) {
    console.log(details);
});

That's because ajax happens asynchronously . 那是因为ajax 异步发生的。 That means getAbc returns before success is invoked, because the request goes over the wire. 这意味着getAbc 调用success 之前返回,因为请求是通过网络进行的。 You need to use details in the success callback, not after the getAbc method returns. 您需要在success回调中使用details ,而不是在getAbc方法返回之后使用。 Alternatively, in success call another method that uses details, and pass details to that method. 或者, success调用另一个使用详细信息的方法,然后将details传递给该方法。

This is due to the way AJAX works. 这是由于AJAX的工作方式。

AJAX requests are asynchronous, which means they do not return immediately. AJAX请求是异步的,这意味着它们不会立即返回。

When you make an AJAX call, a request is made that completes at an unknown time. 当您进行AJAX呼叫时,将发出一个在未知时间完成的请求。

You can use a callback function to handle the results. 您可以使用回调函数来处理结果。

A callback function is a function that gets executed AFTER the response is received from the AJAX request. 回调函数是在收到AJAX请求的响应执行的函数。

You can specify a callback function and pass it to your AJAX call. 您可以指定一个回调函数并将其传递给您的AJAX调用。

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

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