从.ajax调用返回html [英] Returning the html from .ajax call
问题描述
当我尝试通过回调函数返回html时,由于某种原因,我变得未定义:
I'm getting undefined for some reason when I try to return the html via the callback function:
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;
当我警告divContent时(在if语句之前),我变得不确定.也许我在返回数据方面就犯了这个错误?
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?
我也尝试过只是返回数据;同样的事情,当设置为我的变量时,调用此方法后,我变得不确定.
I also tried just return data; same thing, I get undefined after the call to this method when set to my variable.
根据回复更新:
对此进行了尝试,但仍未定义:
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);
}
推荐答案
您无法从回调中返回数据-因为无法保证在函数退出时数据已从函数返回(因为这是一个异步呼叫.)
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 asynchronous call.)
您需要做的是更新回调中的内容,例如:
What you have to do is update the content within the callback, like:
success: function(data) {
$('#dialogDiv').html(data);
},
对话框DIV
附加了id="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);
}
});
}
然后像这样调用它(其中dialogDiv
是表示DIV
的对象,就像您的示例中一样.)
Then call it like so (where dialogDiv
is the object representing the DIV
to update like in your example.)
getDataFromUrl(dialogDiv.attr("href"), dialogDiv);
这篇关于从.ajax调用返回html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!