dtslobe4694 2014-01-24 00:57
浏览 46
已采纳

jQuery获取div内容并通过ajax发送到php脚本

I am trying to get the contents of a div and send that to ajax.

Here is a sample code of ajax that sends data but how can I put the html contents of a div in this post and send it to another php script via ajax?

I need to send ALL the HTML in the "sortable" ui and not just the text.

<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 + ");
       });
 });

Again, This code may be missing some elements but regardless it doesn't work. It's just an example showing what I am trying to do.

  • 写回答

2条回答 默认 最新

  • douceng7070 2014-01-24 01:03
    关注

    I'll use the AJAX method as an example here because I think it's a little clearer about what you want to do. Let's retrieve the li contents and sent it to your PHP script.

    Don't bind to the button element, that is not very specific at all and will bind to any button on the page. Instead, give it an id and bind to that.

    Your main problem is that you're getting the HTML of the ul with id sortable, not the specific li element you're after.

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

    Now in your PHP script, you can access that data with $_POST['yourData']:

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

    EDIT: following having seen your statement: I need to send ALL the HTML in the "sortable" ui and not just the text., if you need the entire ul contents, use what you had originally:

    data: {
        yourData: $('ul#sortable').html();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死