javascript - 如何从 ajax 请求中获取数据以显示在 div 内?

标签 javascript ajax jquery prepend

我无法获取 data从我的ajax请求出现在<div class="l_p_i_c_w"></div>里面。我究竟做错了什么?我知道my_file.php里面的功能有效,因为如果我刷新页面,数据就会显示在应该的位置。

jQuery:

$.ajax({
        type: "POST",
        url: "my_file.php",
        dataType: 'html',
        success: function(data){
            $('div#myID div.l_p_c div.l_p_i_c_w').prepend(data);
        }
});

HTML:

<div class="l_p_w" id="myID">
    <div class="l_p_c">
        <div class="l_p_i_c_w">
       <!-- stuff, or may be empty. This is where I want my ajax data placed. -->
        </div>
    </div>
</div>

CSS:

.l_p_w {
    width:740px;
    min-height:250px;
    margin:0 auto;
    position:relative;
    margin-bottom:10px;
}

.l_p_c {
    position:absolute;
    bottom:10px;
    right:10px;
    width:370px;
    top:60px;
}

.l_p_i_c_w {
    position:absolute;
    left:5px;
    top:5px;
    bottom:5px;
    right:5px;
    overflow-x:hidden;
    overflow-y:auto;
}

最佳答案

我认为,如果您使用 prepend,则需要在附加之前将数据对象包装在 jquery 标签中,例如 $(data),因为 prepend 会附加子对象(对象)

$.ajax({
            type: "POST",
            url: "my_file.php",
            dataType: 'html',
            success: function(data){
                $('div#myID div.l_p_c div.l_p_i_c_w').prepend($(data));
            }
    });

但是,如果您只想使用数据设置 div 的 html,请执行以下操作:

$.ajax({
        type: "POST",
        url: "my_file.php",
        dataType: 'html',
        success: function(data){
            $('div#myID div.l_p_c div.l_p_i_c_w').html(data);
        }
});

第三个选项,尝试 prependTo

http://api.jquery.com/prependTo/

$.ajax({
    type: "POST",
    url: "my_file.php",
    dataType: 'html',
    success: function(data){
        $(data).prependTo($('div#myID div.l_p_c div.l_p_i_c_w'));
    }
});

最后一次尝试:

$.ajax({
            type: "POST",
            url: "my_file.php",
            dataType: 'html',
            success: function(data){
                $('div#myID div.l_p_c div.l_p_i_c_w').html(data + $('div#myID div.l_p_c div.l_p_i_c_w').html());
            }
    });

关于javascript - 如何从 ajax 请求中获取数据以显示在 div 内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13505854/

相关文章:

jquery - 如何根据加载的页面使用 jquery 设置 CSS 样式?

javascript - 如何让用户在小数点前输入一定数量的输入值,在小数点后输入一定数量的输入值

javascript - 为什么 Jquery UI 会删除我的输入框?

javascript - CSS3 + Javascript - 将 -ms-transition :opacity 1s ease-in-out; work in IE 10 alone?

javascript - admin.Firebase.Timestamp 存储时间延迟 7 小时

javascript - extjs中的ajax请求总是执行成功

javascript - 更改旋转动画位置

php - Ajax 文件上传并预览

php - 如何允许 php 文件仅由站点调用,而不是通过 Inspect Element 或 URL 调用

javascript - 无法在 AngularJS View 上呈现 Jsonresult