简体   繁体   English

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

[英]Javascript callback from custom jQuery AJAX function

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); AJAX请求触发正常,服务器返回有效的JSON,但console.log(json); returns undefined and the js crashes when it gets to json.pagename . 返回undefined ,并且js到达json.pagename时崩溃。 The first console.log(parsed) also returns good data so it's just a problem with the return (I think). 第一个console.log(parsed)所以它只是一个问题也返回好的数据return (我认为)。

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. 我将load_page移到了全局命名空间'cos中,我需要它在那儿。 The console.log(parsed) returns what seems to be a valid json object, but console.log(parsed.content) yields undefined . console.log(parsed)返回似乎是有效的json对象,但console.log(parsed.content)产生undefined #content isn't being set either. #content也未设置。 Any ideas? 有任何想法吗? I'll be glad to do any testing. 我很乐意做任何测试。

Any help is greatly appreciated! 任何帮助是极大的赞赏!

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();
   }
});

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); 在load_page函数的定义内,没有“ return”语句,至少不是直接这样做,因此至少要执行var json = load_page(page); you'll end up with json = undefined. 您最终会得到json = undefined。 Ideally you should re-organize your code a little. 理想情况下,您应该稍微重新组织代码。 There is more than one way of doing this but here is one: 这样做的方法不止一种,但这里有一种:

(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);
})();

The issue is because jQuery issues ajax calls asynchronously by default. 问题是因为jQuery默认情况下异步发出ajax调用。 Hence the next statement is executed even before the ajax call is complete after 因此,即使在ajax调用完成之后也要执行下一条语句
var json = load_page(page);. 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. 您可以通过在config参数中传递async:false并在回调函数中处理retun值来使调用同步。

try console.log before parsing to check what data is exactly coming. 在解析之前尝试console.log来检查确切的数据。 is it valid json 它是有效的json吗

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

It's an AJAX call, as in, the code is completed asynchronously. 这是一个AJAX调用,例如,代码是异步完成的。 You need to put the console.log and any other use of the json variable in the success function. 您需要将console.log以及json变量的任何其他用法放入成功函数中。

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

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