簡體   English   中英

jQuery / ajax頁面更新幫助

[英]JQuery/ajax page update help pls

嗨,我是Jquery / ajax的新手,並且需要有關最后(我認為)代碼的幫助。 我有一個可拖動項(jQuery ui.draggable),將其放置在放置區中時會更新mysql表-可以使用以下方法:

    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. 顯示數據庫表中具有更新后的帖子的列表(即,通過拖放操作)

有很多方法可以做到這一點。 我可能要做的就是讓PHP腳本輸出需要顯示的內容。 這可以通過JSON(基本上是用JavaScript語法編碼的數據)或原始HTML來完成。

如果要使用原始HTML:

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.
        }
    });
}

如果使用JSON,則過程本質上是相同的,除了您必須自己在JavaScript中構造新的HTML元素(顯然,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);
}

我不了解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*/} });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM