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条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?