jquery ajax获取HTML但不会返回它

时间:2013-01-31 20:06:46

标签: javascript jquery jquery-deferred

  

可能重复:
  How to return the response from an AJAX call from a function?

我正在尝试通过ajax获取一些HTML内容。但由于某种原因,尽管HTML使其成为ajax函数,但当我尝试将其用作返回值时,我得到undefined

像这样:

function get_additional_options(name) {

    var post = $.ajax({
            type: 'post',
            url: 'order_queries_templates/html/' + name + '_additional_options.php?<?=time()?>',
            //data:'product_id=' + product_id,
            dataType: 'html'

            });

    post.done(function (p) {
        console.log(p); //prints out all the HTML just as I would expect
        return p;
    });
}

但是当我尝试将HTML添加到我的页面时,就像这样

if (has_additional_options == "t"){
    var html_to_append = get_additional_options(name);
    console.log(html_to_append); // undefined

}

如果我使用done()方法,或者只是将值作为成功回调返回,则结果相同。我的错误是什么?

2 个答案:

答案 0 :(得分:3)

您无法从异步调用的函数返回值。

您应该返回post(即$.ajax的结果),然后在您的函数之外注册.done个处理程序

function get_additional_options(name) {
    return $.ajax({
        ...
    });
};

if (has_additional_options == "t") {
     get_additional_options(name).done(function(p) {
         console.log(p);
     });
     // NB: code execution continues here immediately - don't do anything
     //     else here - all further stuff must be done in the above callback
 }

答案 1 :(得分:0)

您将在匿名函数中返回HTML值。 你基本上把它传递给post.done方法。

在这种情况下使用事件可能更好,因为你在这里运行异步代码。

function get_additional_options(name) {

    var post = $.ajax({
            type: 'post',
            url: 'order_queries_templates/html/' + name + '_additional_options.php?<?=time()?>',
            //data:'product_id=' + product_id,
            dataType: 'html'

            });

    post.done(function (p) {
        $("body").trigger("html_loaded",[p]);
    );
}

$("body").on("html_loaded", function (htmlData) {

    // Do something with your HTML data here.
    $(this).append(htmlData);

});