如何用Ajax响应中的javascript替换内容

How to replace content with javascript from Ajax response

本文关键字:javascript 替换 何用 Ajax 响应      更新时间:2024-06-05

我不想用从分部视图获得的新数据替换索引视图中div的一个部分。我得到了一个正确的答案,我在萤火虫身上看到了这一点。目前,我只在成功时显示一个警告窗口,表明它正在发挥作用。Bellow是我的Ajax代码,也是我得到的响应的一部分(ul中有20个列表组项)。那么,我是否必须像在我的视图中那样为每个div编写javascript代码,或者还有其他选项?也许可以举几个例子?

问候!

<script>
        function testAjax() {
            debugger;
            $.ajax({
                url: "@Url.Content("~/Controller/MyAction")",
                data: "searchString=search",
                type: "Post",
                beforeSend: function () {
                    //Code for before send whatever you have to do.
                },
                success: function (data) {
                    alert("It's Working!");
                },
                error: function (response) {
                    //Your code when error ocure
                    alert(response.responseText);
                },
                failure: function (response) {
                    //your code for failure
                    alert(response.responseText);
                }
            })
        }
    </script>

我的回答:

<ul class="list-group infinite-scroll">                       
        <li class="list-group-item col-md-6">
            <div class="noo-event-featured-item grow">
                <div class="sc-event-content">
                    <h3><a href="/Controller/Podrobnosti/73" onclick="checkCookie();">text</a></h3>
                    <div class="bottom">
                        <div class="create-date">
                            <span>
                                date
                            </span>
                        </div>
                    </div>
                </div>
                <div class="sc-event-item">
                    <div class="event-thumbnail">
                        <a href="link" >
                            <img src="image link">
                        </a>
                        <div class="sc-meta">
                            <span class="sc-date"><i class="fa fa-clock-o"></i><span> text</span></span>
                            <span class="sc-address">
                                <i class="fa  fa-map-marker" style="padding-left: 3px;"></i>Place<span class="tribe-address">
                                    <span class="tribe-street-address">Street</span><span class="tribe-delimiter"
>, </span>
                                    <span class="tribe-locality">Country</span>
                                </span>
                            </span>                         
                        </div>
                    </div>
                </div>               
            </div>
        </li>
</ul>

谢谢大家,我已经想通了。您必须在分割$(".divid").replaceWith(data); 之前使用一个点

如果你的响应是html代码(纯文本),你可以尝试在你的成功函数中使用这样的东西:

$('yourDiv').html(data);//replace child nodes