2014-01-24 88 views
1

我想獲取div的內容並將其發送到ajax。jQuery獲取div內容並通過ajax發送到php腳本

以下是發送數據的ajax示例代碼,但如何在本文中將div的html內容通過ajax發送給另一個php腳本?

我需要發送「排序」用戶界面中的所有HTML,而不僅僅是文本。

<ul id="sortable"> 

<li class="ui-state-default">Hello, please send me to Ajax! :)</li> 

</ul> 


$("button").click(function() 
    { 
     $.post("get_sorted_content.php", // Example script 
     { 

     data: $("#sortable").html(); // My NEEDED content - Does not work! 

    function(data) 
     { 

     alert("Data: " + data + "); 
     }); 
}); 

再次,此代碼可能會丟失一些元素,但不管它不起作用。這只是一個顯示我想要做什麼的例子。

回答

2

這裏我將使用AJAX方法作爲示例,因爲我認爲它對於您想要執行的操作有點清晰。讓我們檢索li內容並將其發送到您的PHP腳本。

不要綁定到button元素,它根本不是特定的,並且會綁定到頁面上的任何按鈕。相反,給它一個id並綁定到那個。

你的主要問題是,你得到UL的HTML ID爲sortable,而不是具體的li元素你之後。

<ul id="sortable"> 
    <li class="ui-state-default">Hello, please send me to Ajax! :)</li> 
</ul> 

<button id="clickme">Click me!</button> 

// bind to the button with clickme ID 
$("button#clickme").click(function() { 
    $.ajax({ 
     url: 'get_sorted_content.php', 
     type: 'POST', // GET is default 
     data: { 
      yourData: $('#sortable li').html() 
      // in PHP, use $_POST['yourData'] 
     }, 
     success: function(msg) { 
      alert('Data returned from PHP: ' + msg); 
     }, 
     error: function(msg) { 
      alert('AJAX request failed!' + msg); 
     } 
    }); 
}); 

現在,在你的PHP腳本,你可以用$_POST['yourData']訪問數據:

<?php 
// get_sorted_content.php 
if(!empty($_POST['yourdata'])) 
    echo 'data received!'; 
else 
    echo 'no data received!'; 
?> 

編輯:繼在看到你的發言:I need to send ALL the HTML in the "sortable" ui and not just the text.,如果你需要整個ul內容,使用你原來的東西:

data: { 
    yourData: $('ul#sortable').html(); 
} 
2

$.post調用需要改變如下:

$.post('get_sorted_content.png', 
      { data: $("#sortable").html()}, 
      function(data){ 
       //data is whatever you send back from php script. 
      } 
    ); 

如果$("#sortable").html()不工作,試圖逃跑像HTML:

escape($("#sortable").html()); 
相關問題