dongyan8929 2013-03-04 22:36
浏览 21
已采纳

没有嵌套的DIV,JQuery AJAX将无法工作,为什么?

Imagine the following index.php :

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>

    <form id="MY_FORM" action="./index.php" method="get">
        <input name="var_name">
        <input type="submit">
    </form> 

    <!-- <div> -->
    <div id="MY_CONTENT">
        <?php
            var_dump( $_GET ); 
        ?>
    </div>
    <!-- </div> -->

    <script type="text/javascript">

        $('#MY_FORM').submit(function()
        {
            var form = $(this);
            $.get('./', form.serialize(), function(data)
            {
                var updated = $('#MY_CONTENT', data);
                $('#MY_CONTENT').replaceWith(updated);
            });
            return false;
        });

    </script>

</body>
</html>

There is a simple AJAX form. When this form is submited then MY_CONTENT should be refreshed with AJAX (hence form's action="./index.php"). Question: I found the code working only when MY_CONTENT div is enclosed in the another div.

I placed the

<!-- <div> -->
<!-- </div> -->

around MY_CONTENT. this must be changed to div to get the script working.
Why does MY_CONTENT have to be wrapped in a div?

  • 写回答

2条回答 默认 最新

  • dongyou8368 2013-03-04 22:38
    关注

    This happens because data contains all elements that were children of the head and body tags, but not the head/body itself. you can get rid of the wrapper by using

    var updated = $(data).filter("#MY_CONTENT")
    

    instead since it is a direct child of the body tag after you get rid of the wrapper.

    Another solution (as pointed out by Fabrício Matté) is to only return the target html if the request is an ajax request.

    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && Strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        var_dump( $_GET );
    }
    else {
       ... rest of your page ...
    

    then you can just do

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

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入