2010-01-09 67 views
1

嗨,我是Jquery/ajax的新手,需要幫助完成最終(我認爲)的一段代碼。 我有一個可拖動的項目(JQuery的ui.draggable),當放入拖放區更新一個MySQL表 - 這樣的作品,這一點:JQuery/ajax頁面更新幫助

function addlist(param) 
{ 
    $.ajax({ 
    type: "POST", 
    url: "ajax/addtocart.php", 
    data: 'img='+encodeURIComponent(param), 
    dataType: 'json', 
    beforeSend: function(x){$('#ajax-loader').css('visibility','visible');} 



    }); 
} 

但我不能讓它做的是「刷新」另一頁面/同一頁面來顯示更新的結果。 簡單來說,我想

  1. 將&下降
  2. 更新數據庫
  3. 顯示加載GIF
  4. 顯示錶從數據庫表更新後(即從拖動&下降)

回答

0

我不知道PHP,但你想要的是addtocart.php回饋某種迴應(回聲?) ,你會採取照顧。

$.ajax({ 
type: "POST", 
url: "ajax/addtocart.php", 
data: 'img='+encodeURIComponent(param), 
dataType: 'json', 
beforeSend: function(x){$('#ajax-loader').css('visibility','visible'); 

success: function(response){ /* use the response to update your html*/} }); 
1

這樣做有很多方法。我可能會做的是讓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); 
}