更新:對不起,錯過了對話是部分你最關心的。最後請參閱特定於對話框的添加。
原來的答覆:
從一個變量的HTML加載到一個元素,可以使用html
功能:
var markup = "This is <strong>HTML</strong>";
$("#targetElement").html(markup);
因此,如果您加載通過AJAX該標記,可能是:
$.ajax({
url: "your.url",
success: function(data) {
$("#targetElement").html(data);
},
error: function() {
// ... deal with error ...
}
});
如果你真的只是搶佔了所有的內容有,這就是你所用的load
功能的作用:
$("#targetElement").load("your.url");
...但如果你想先做些別的事情吧,用ajax
。
例如,假設您使用JSON表示法從服務器加載一些數據。假設數據是這樣的:對於對話框
$.ajax({
url: "http://jsbin.com/urebu5",
dataType: "json",
success: function(data) {
// Use the de-serialized object's properties
// to append HTML to the body
$("<p>").html(data.foo).appendTo(document.body);
$("<p>").html(data.bar).appendTo(document.body);
},
error: function(xhr, statusText, ex) {
$("<p>Error running <tt>ajax</tt> call</p>").appendTo(
document.body
);
}
});
Live example
更新:
{
"foo": "I'm the foo value",
"bar": "I'm the bar value"
}
你可以做到這一點
由於jQuery UI的對話框只使用元素作爲基礎,上面的ap層數它們爲好,這裏是一個例子假設對話框元素具有id
值「模式,對話」和最初是隱藏的(見下文從頭開始創建對話框):
function showDialog(content) {
// Get the dialog element
var dlgElement = $("#modal-dialog");
// Update the dialog with the content
dlgElement.find('p:first').html(content);
// Show it
dlgElement.dialog({
height: 140,
modal: true
});
}
因此,使用從我們ajax
撥打以上:
// Load our content
$.ajax({
url: "http://jsbin.com/urebu5",
dataType: "json",
success: function(data) {
// Show the 'foo' part of the data
showDialog(data.foo);
},
error: function(xhr, statusText, ex) {
// Show the error
showDialog("Error running <tt>ajax</tt> call");
}
});
Live example
如果要從頭開始創建對話框,只需創建的元素,然後一定要刪除它們完成時:
function createDialog(title, content) {
// Create our dialog structure
return $("<div>")
.css("display", "none")
.attr("title", title)
.html("<p>" + content + "</p>")
.appendTo(document.body);
}
function showDialog(dlg, destroy) {
var opts = {
height: 140,
modal: true
};
if (destroy) {
opts.close = function(event, ui) {
$(this).remove();
};
}
dlg.dialog(opts);
}
用途:
// Load our content
$.ajax({
url: "http://jsbin.com/urebu5",
dataType: "json",
success: function(data) {
// Create a dialog using 'foo' part of the data
var dlg = createDialog("Foo Data", data.foo);
// Show it
showDialog(dlg, true);
},
error: function(xhr, statusText, ex) {
// Create a dialog using 'foo' part of the data
var dlg = createDialog(
"Foo Data - Error",
"Error running <tt>ajax</tt> call"
);
// Show it
showDialog(dlg, true);
}
});
Live example
感謝答覆.. – Parag 2011-02-11 06:22:20