這樣做有很多方法。我可能會做的是讓PHP腳本輸出需要顯示的內容。這可以通過JSON(基本上是用JavaScript語法編碼的數據)或通過原始HTML完成。
如果你使用原始的HTML:如果使用JSON
function addlist(param)
{
$.ajax(
{
type: 'POST',
url: 'ajax/addtocart.php',
data: 'img=' + encodeURIComponent(param),
dataType: 'html',
beforeSend: function()
{
$('#ajax-loader').css('visibility','visible');
},
success: function(data, status)
{
// Process the returned HTML and append it to some part of the page.
var elements = $(data);
$('#some-element').append(elements);
},
error: function()
{
// Handle errors here.
},
complete: function()
{
// Hide the loading GIF.
}
});
}
,該過程將基本上是相同的,除了你必須自己構建新的HTML元素在JavaScript(和輸出來自PHP腳本必須使用json_encode
進行編碼,顯然)。您的success
回調可能看起來像這樣:
function(data, status)
{
// Get some properties from the JSON structure and build a list item.
var item = $('<li />');
$('<div id="div-1" />').text(data.foo).appendTo(item);
$('<div id="div-2" />').text(data.bar).appendTo(item);
// Append the item to some other element that already exists.
$('#some-element').append(item);
}