来自自定义jQuery AJAX函数的Javascript回调

时间:2022-12-08 19:48:13

I have this jQuery code

我有这个jQuery代码

(function () {
    function load_page (pagename) {
        $.ajax({
            url: "/backend/index.php/frontend/pull_page/",
            type: "POST",
            data: {page: pagename},
            success: function (json) {
                var parsed = $.parseJSON(json);
                console.log(parsed);
                return parsed;
            },
            error: function (error) {
                $('#content').html('Sorry, there was an error: <br>' + error);
                return false;
            }
        });
    }
    ...
    var json = load_page(page);
    console.log(json);
    if (json == false) {
        $('body').fadeIn();
    } else {
        document.title = json.pagename + ' | The Other Half | freddum.com';
        $("#content").html(json.content);
        $('#header-navigation-ul a:Contains('+page+')').addClass('nav-selected');
        $('body').fadeIn();
    }
})();

and, guess what, it doesn't work. The AJAX request fires fine, and the server returns valid JSON but the console.log(json); returns undefined and the js crashes when it gets to json.pagename. The first console.log(parsed) also returns good data so it's just a problem with the return (I think).

而且,猜猜看,它不起作用。 AJAX请求触发正常,服务器返回有效的JSON但是console.log(json);返回undefined,当js到达json.pagename时js崩溃。第一个console.log(已解析)也返回了良好的数据,因此它只是返回的一个问题(我认为)。

I knew I was clutching at straws and would be extremely if this worked, but it doesn't. To be honest, I don't know how to program callback functions for this situation.

我知道我紧抓着稻草,如果这种方法有效的话会非常有用,但事实并非如此。说实话,我不知道如何为这种情况编写回调函数。

EDIT: This is my now updated code, which doesn't work either.

编辑:这是我现在更新的代码,也不起作用。

function load_page (pagename, callback) {
    $.ajax({
        url: "/backend/index.php/frontend/pull_page/",
        type: "POST",
        data: {page: pagename},
        success: function (json) {
            callback(json);
        },
        error: function (error) {
            $('#content').html('Sorry, there was an error: <br>' + error);
            var json = false;
            callback(json);
        }
    });
}
(function () {
    $('body').hide();
    var page = window.location.hash.slice(1);
    if (page == "") page = 'home';
    load_page(page, function(json) {
        var parsed = $.parseJSON(json);
        console.log(parsed);
        if (json.pagename == "" || json.pagename == null) {
            document.title = 'Page Not Found | The Other Half | freddum.com';
            $('body').fadeIn();
        } else {
            document.title = parsed.pagename + ' | The Other Half | freddum.com';
            $("#content").html(parsed.content);
            $('#header-navigation-ul a:Contains('+page+')').addClass('nav-selected');
            $('body').fadeIn();
        }    
    });

})();

I moved load_page into global namespace 'cos I needed it to be there. The console.log(parsed) returns what seems to be a valid json object, but console.log(parsed.content) yields undefined. #content isn't being set either. Any ideas? I'll be glad to do any testing.

我将load_page移动到全局命名空间'因为我需要它在那里。 console.log(已解析)返回看似有效的json对象,但console.log(parsed.content)产生undefined。 #content也没有被设置。有任何想法吗?我很乐意做任何测试。

Any help is greatly appreciated!

任何帮助是极大的赞赏!

5 个解决方案

#1


8  

Because Ajax requests are asynchronous, the code following the $.ajax function invocation still executes, whether the request is finished or not, so you should accept a callback as a argument to load_page that is invoked when the request is finished:

因为Ajax请求是异步的,所以$ .ajax函数调用之后的代码仍会执行,无论请求是否完成,因此您应该接受回调作为请求完成时调用的load_page的参数:

function load_page (pagename, callback) {
    $.ajax({
        url: "/backend/index.php/frontend/pull_page/",
        type: "POST",
        data: {page: pagename},
        success: function (json) {
            var parsed = $.parseJSON(json);
            console.log(parsed);
            callback(parsed); //bingo
        },
        error: function (error) {
            $('#content').html('Sorry, there was an error: <br>' + error);
        }
    });
}

load_page(page, function(json) {
   console.log(json);
   if (json == false) {
      $('body').fadeIn();
   } else {
      document.title = json.pagename + ' | The Other Half | freddum.com';
      $("#content").html(json.content);
      $('#header-navigation-ul a:Contains('+page+')').addClass('nav-selected');
      $('body').fadeIn();
   }
});

#2


2  

Inside the definition of the load_page function there is no "return" statement, not directly at least hence by doing a var json = load_page(page); you'll end up with json = undefined. Ideally you should re-organize your code a little. There is more than one way of doing this but here is one:

在load_page函数的定义中,没有“return”语句,至少不是直接通过var json = load_page(page);你最终会得到json = undefined。理想情况下,您应该稍微重新组织您的代码。这样做的方法不止一种,但这里有一种方法:

(function () {
    function mySuccess(json) {
        var parsed = $.parseJSON(json);
        console.log(json);
        console.log(parsed);
        document.title = parsed.pagename + " | The Other Half | freddum.com";
        $("#content").html(parsed.content);
        $("#header-navigation-ul a:Contains(" + page + ")").addClass("nav-selected");
        $("body").fadeIn();
    }
    function myFailure(error) {
        $('#content').html('Sorry, there was an error: <br>' + error);
        $("body").fadeIn();
    }
    function load_page(pagename, onSuccess, onFailure) {
        $.ajax({
            url: "/backend/index.php/frontend/pull_page/",
            type: "POST",
            data: {
                page: pagename
            },
            success: onSuccess,
            error: onFailure
        });
    }
    load_page(page, mySuccess, myFailure);
})();

#3


1  

The issue is because jQuery issues ajax calls asynchronously by default. Hence the next statement is executed even before the ajax call is complete after
var json = load_page(page);. You can either make the calls synchronous by passing async:false in the config parameters and dealing with the retun value in the callback function.

问题是因为jQuery默认情况下异步发出ajax调用。因此,在var json = load_page(page);之后,即使在ajax调用完成之前,也会执行下一个语句。您可以通过在config参数中传递async:false并处理回调函数中的retun值来使调用同步。

#4


0  

try console.log before parsing to check what data is exactly coming. is it valid json

在解析之前尝试console.log来检查确切的数据。这是有效的json

success: function (json) { console.log(json); var parsed = $.parseJSON(json);

成功:function(json){console.log(json); var parsed = $ .parseJSON(json);

#5


0  

It's an AJAX call, as in, the code is completed asynchronously. You need to put the console.log and any other use of the json variable in the success function.

这是一个AJAX调用,因为代码是异步完成的。您需要将console.log和json变量的任何其他用法放在success函数中。

#1


8  

Because Ajax requests are asynchronous, the code following the $.ajax function invocation still executes, whether the request is finished or not, so you should accept a callback as a argument to load_page that is invoked when the request is finished:

因为Ajax请求是异步的,所以$ .ajax函数调用之后的代码仍会执行,无论请求是否完成,因此您应该接受回调作为请求完成时调用的load_page的参数:

function load_page (pagename, callback) {
    $.ajax({
        url: "/backend/index.php/frontend/pull_page/",
        type: "POST",
        data: {page: pagename},
        success: function (json) {
            var parsed = $.parseJSON(json);
            console.log(parsed);
            callback(parsed); //bingo
        },
        error: function (error) {
            $('#content').html('Sorry, there was an error: <br>' + error);
        }
    });
}

load_page(page, function(json) {
   console.log(json);
   if (json == false) {
      $('body').fadeIn();
   } else {
      document.title = json.pagename + ' | The Other Half | freddum.com';
      $("#content").html(json.content);
      $('#header-navigation-ul a:Contains('+page+')').addClass('nav-selected');
      $('body').fadeIn();
   }
});

#2


2  

Inside the definition of the load_page function there is no "return" statement, not directly at least hence by doing a var json = load_page(page); you'll end up with json = undefined. Ideally you should re-organize your code a little. There is more than one way of doing this but here is one:

在load_page函数的定义中,没有“return”语句,至少不是直接通过var json = load_page(page);你最终会得到json = undefined。理想情况下,您应该稍微重新组织您的代码。这样做的方法不止一种,但这里有一种方法:

(function () {
    function mySuccess(json) {
        var parsed = $.parseJSON(json);
        console.log(json);
        console.log(parsed);
        document.title = parsed.pagename + " | The Other Half | freddum.com";
        $("#content").html(parsed.content);
        $("#header-navigation-ul a:Contains(" + page + ")").addClass("nav-selected");
        $("body").fadeIn();
    }
    function myFailure(error) {
        $('#content').html('Sorry, there was an error: <br>' + error);
        $("body").fadeIn();
    }
    function load_page(pagename, onSuccess, onFailure) {
        $.ajax({
            url: "/backend/index.php/frontend/pull_page/",
            type: "POST",
            data: {
                page: pagename
            },
            success: onSuccess,
            error: onFailure
        });
    }
    load_page(page, mySuccess, myFailure);
})();

#3


1  

The issue is because jQuery issues ajax calls asynchronously by default. Hence the next statement is executed even before the ajax call is complete after
var json = load_page(page);. You can either make the calls synchronous by passing async:false in the config parameters and dealing with the retun value in the callback function.

问题是因为jQuery默认情况下异步发出ajax调用。因此,在var json = load_page(page);之后,即使在ajax调用完成之前,也会执行下一个语句。您可以通过在config参数中传递async:false并处理回调函数中的retun值来使调用同步。

#4


0  

try console.log before parsing to check what data is exactly coming. is it valid json

在解析之前尝试console.log来检查确切的数据。这是有效的json

success: function (json) { console.log(json); var parsed = $.parseJSON(json);

成功:function(json){console.log(json); var parsed = $ .parseJSON(json);

#5


0  

It's an AJAX call, as in, the code is completed asynchronously. You need to put the console.log and any other use of the json variable in the success function.

这是一个AJAX调用,因为代码是异步完成的。您需要将console.log和json变量的任何其他用法放在success函数中。