jQuery 从 .ajax 调用返回 html

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2637762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:55:15  来源:igfitidea点击:

Returning the html from .ajax call

jquery

提问by PositiveGuy

I'm getting undefined for some reason when I try to return the html via the callback function:

当我尝试通过回调函数返回 html 时,由于某种原因,我变得未定义:

function getDataFromUrl(urlWithContent)
{  
    // jQuery async request
    $.ajax(
    {
        url: urlWithContent,
        dataType: "html",
        success: function(data) {
                                    return $('.result').html(data);
                                },
        error: function(e) 
        {
            alert('Error: ' + e);
        }
    });
}

I know I'm getting data back, I see it in firebug in the response and also when I alert out the data, I see the entire page content come up in the alert box.

我知道我正在取回数据,我在响应中的萤火虫中看到它,而且当我警告数据时,我看到整个页面内容都出现在警告框中。

When I call my function, I am doing the following:

当我调用我的函数时,我正在执行以下操作:

var divContent = getDataFromUrl(dialogDiv.attr("href"));

if(divContent)
    dialogDiv.innerHTML = divContent;

when I alert out the divContent (before the if statement) I'm getting undefined. Maybe I'm just going about this wrong on how I'm returning back the data?

当我提醒 divContent (在 if 语句之前)时,我变得未定义。也许我只是在如何返回数据方面犯了这个错误?

I also tried just return data; same thing, I get undefined after the call to this method when set to my variable.

我也试过只返回数据;同样的事情,当设置为我的变量时,在调用此方法后我得到未定义。

Updated per responses:

根据回复更新:

Tried this, still getting undefined:

试过这个,仍然未定义:

function getDataFromUrl(urlWithContent, divToUpdate)
{  
    $.ajax(
    {
        url: urlWithContent,
        aSync: false,
        dataType: "html",
        success: function(data) {
                                    divToUpdate.innerHTML = data;
                                },
        error: function(e) 
        {
            alert('Error: ' + e);
        }
    });
}

I called it from within another function like this:

我从另一个函数中调用它,如下所示:

var divContent = "";

if (dialogDiv.attr("href"))
{
    getDataFromUrl(dialogDiv.attr("href"), divContent);
}

回答by Andy Shellam

You cannot return data from the callback - because there's no guarantee that the data will have been returned back from the function at the time the function exits (as it's an asynchronouscall.)

您不能从回调中返回数据 - 因为不能保证在函数退出时数据会从函数返回(因为它是一个异步调用。)

What you have to do is update the content within the callback, like:

您需要做的是更新回调中的内容,例如:

success: function(data) {
    $('#dialogDiv').html(data);
},

where your dialog DIVhas id="dialogDiv"attached to it.

您的对话框DIVid="dialogDiv"附加到它的位置。

I think you can also modify your function to take the object to update when the call completes like so:

我认为您还可以修改您的函数以在调用完成时更新对象,如下所示:

function getDataFromUrl(urlWithContent, divToUpdate)
{  
    // jQuery async request
    $.ajax(
    {
        url: urlWithContent,
        dataType: "html",
        success: function(data) {
            divToUpdate.innerHTML = data;
        },
        error: function(e) 
        {
            alert('Error: ' + e);
        }
    });
}

Then call it like so (where dialogDivis the object representing the DIVto update like in your example.)

然后像这样调用它(在你的例子中dialogDiv代表DIV更新的对象在哪里。)

getDataFromUrl(dialogDiv.attr("href"), dialogDiv);

回答by tvanfosson

The ajax call runs asynchronously. Therefore your function returns (by dropping out of the end of the block) before your ajax call completes. You have two ways to handle this. Add the aSync: falseoption to force the ajax call to run synchronously or use a callback to your function that can be executed when the ajax call completes. I'd prefer the latter.

ajax 调用异步运行。因此,您的函数在 ajax 调用完成之前返回(通过退出块的末尾)。你有两种方法来处理这个问题。添加aSync: false选项以强制 ajax 调用同步运行或使用回调函数,该回调函数可在 ajax 调用完成时执行。我更喜欢后者。

function setDataFromUrl(urlWithContent,callback) 
{   
    // jQuery async request 
    $.ajax( 
    { 
        url: urlWithContent, 
        dataType: "html", 
        success: function(data) { 
                                    callback(data);
                                }, 
        error: function(e)  
        { 
            alert('Error: ' + e); 
        } 
    }); 
}

setDataFromUrl(dialogAnchor.attr("href"), function(data) {
     dialogDiv.html(data);
});

or even better, unless you're sharing this code in lots of places:

甚至更好,除非您在很多地方共享此代码:

var dialogDiv = $('div.dialog');
var dialogAnchor = dialogDiv.find('a');
// jQuery async request 
$.ajax( 
{ 
    url: dialogAnchor.attr('href'), 
    dataType: "html", 
    success: function(data) { 
                                dialogDiv.html(data);
                            }, 
    error: function(e)  
    { 
        alert('Error: ' + e); 
    } 
});

回答by Raja

Why dont you try this:

为什么不试试这个:

function getDataFromUrl(urlWithContent)
{  
    // jQuery async request
    $.ajax(
    {
        url: urlWithContent,
        dataType: "html",
        success: function(data) {
                                    $('#dialogDiv').html(data);
                                },
        error: function(e) 
        {
            alert('Error: ' + e);
        }
    });
}

And just call the function and not assign it to any variable.

只需调用该函数,而不将其分配给任何变量。

HTH

HTH