【问题标题】:Ajax replace new arraylist without refresh pageAjax替换新的arraylist而不刷新页面
【发布时间】:2017-09-03 23:38:07
【问题描述】:

我是新的 ajax,如何将 ${phList} 替换为新的 arraylist,以便 ajax 可以帮助我更新内容而不刷新整个页面。

ajax 将触发控制器检索数据并存储在arraylist 中,然后将arraylist 传递给ajax。 Ajax 会更新jsp 中的内容。如果有从数据库检索的记录,下一步 forEach 循环将生成带有值的列和复选框。

任何解决方案,希望这个解决方案可以帮助别人。谢谢!

myJsp.jsp

<select id="selected_year" name="selected_year" class="form-control">
    <c:forEach var="line" items="${yearlist}">
        <c:choose>
            <c:when test="${refreshInd ge 0 and line eq refreshInd}">
                <option selected="selected"><c:out value="${line}" />
                </option>
            </c:when>
            <c:otherwise>
                <option><c:out value="${line}" /></option>
            </c:otherwise>
        </c:choose>

    </c:forEach>
</select>

<c:forEach var="ph" items="${phList}" varStatus="PHstatus">
      <div class="row">
        <div class="col-md-4">
          <form:input path="phList[${PHstatus.index}].holidayDesc" class="form-control col-md-5" value="${ph.holidayDesc}" />
        </div>

        <div class="col-md-3">
          <form:input path="phList[${PHstatus.index}].startDate" class="form-control" value="${ph.startDate}" id="calendar1" placeholder="dd/mm/yyyy" onkeypress="return noAlphabet(event)" />
        </div>

        <div class="col-md-3">
          <form:input path="phList[${PHstatus.index}].endDate" class="form-control" value="${ph.endDate}" id="calendar2" placeholder="dd/mm/yyyy" onkeypress="return noAlphabet(event)" />
        </div>

        <div class="col-md-2">
          <form:checkbox path="phList[${PHstatus.index}].checkboxDel" value="" class="cbposition" />
        </div>
      </div>
      <br>
    </c:forEach>

在我更改 selected_year 以触发 ajax 后,它运行良好,但 :success 函数(响应)无法运行。我想删除现有的 ${phList} 并通过替换上面 jsp 中的 ${phList} 来更新新的数组列表。

myJavascript.js

$(function($) {
    $("#selected_year").change(function(){
        var selectedText = $(this).find("option:selected").text();
        var $form = $(this);
        var action = $form.find('.send').val();

        var list[];
        var array[];

        $.ajax("holiday/pubholiday.json?" , {
            method: "GET",
            accepts: "application/json",
            dataType: "json",
            data: $form.serialize() + '&selectedText=' + selectedText,
            success: function(response) {
                $("#phList").remove()
                $(JSON.stringify(response))
    //how to pass the response which is my new arraylist to replace the ${phList}
              },
        }).done(function(data) {
            console.log(data)
            alert("Data Sent" + selectedText)
        })
        .fail(function(jqXHR, textStatus, errorThrown) {
            var errorMessage = "";
            if (jqXHR.status == 401) {
                errorMessage = "Your session has expired. Please <a href=\"<spring:url value='/login'/>\">login</a> again.";
            }else if(jqXHR.status == 500){
                console.log(jqXHR.status);
                   console.log(jqXHR.responseText);
                   console.log(thrownError);
            }else {
                try {
                    var errorJson = JSON.parse(jqXHR.responseText);
                    errorMessage = errorJson.error;

                } catch (e) {
                errorMessage = errorThrown || textStatus;
            }
            }
            });
    })
});

这是数组列表中的对象模型存储。每条记录都将包含对象模型数据。

model.java

    public class PubHoliday {
    private int year;
    private String holidayID;
    private String holidayDesc;
    private String startDate;
    private String endDate;
    private boolean checkboxDel;
    private String selected_year;
    private int refreshInd;

    public int getYear() {
        return year;
    }
    public void setYear(int year) {
        this.year = year;
    }
    public String getHolidayID() {
        return holidayID;
    }
    public void setHolidayID(String holidayID) {
        this.holidayID = holidayID;
    }
    public String getHolidayDesc() {
        return holidayDesc;
    }
    public void setHolidayDesc(String holidayDesc) {
        this.holidayDesc = holidayDesc;
    }
    public String getStartDate() {
        return startDate;
    }
    public String getEndDate() {
        return endDate;
    }
    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }
    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }
    public boolean getCheckboxDel() {
        return checkboxDel;
    }
    public void setCheckboxDel(boolean checkboxDel) {
        this.checkboxDel = checkboxDel;
    }
    public String getSelected_year() {
        return selected_year;
    }
    public void setSelected_year(String selected_year) {
        this.selected_year = selected_year;
    }
    public int getRefreshInd() {
        return refreshInd;
    }
    public void setRefreshInd(int refreshInd) {
        this.refreshInd = refreshInd;
    }
}

【问题讨论】:

  • 请详细说明问题。您提供了相当多的代码,但没有提及哪些有效或无效以及哪些需要更改

标签: javascript jquery ajax


【解决方案1】:

首先,您需要将&lt;c:forEach var="ph" items="${phList}" varStatus="PHstatus"&gt; 包装成带有id 的div,例如:

<div id="list_holidays">
<c:forEach var="ph" items="${phList}" varStatus="PHstatus">
  .......
</c:forEach>
</div>

然后在成功的ajax代码中 - 空 div#list_holidays - 获取结果,每一行,创建新的div,追加到div#list_holidays

success: function(response) {
    var wrapper = $('#list_holidays');
    wrapper.html('');
    //->foreach response result
    //   -> $('div').html(your template).appendTo(wrapper)
}

【讨论】:

  • 它工作了一半。在我尝试包装后,它会覆盖我的整个网页,并且循环的模板是重复的。
【解决方案2】:

JSP 是服务器端渲染。意思是,当接收到请求时,服务器使用变量${phList} 呈现动态 HTML 页面并将该页面发送到浏览器。 Ajax 是您的 javascript 在浏览器中发出的请求。因此,浏览器无法直接知道或更改变量$(phList} 并影响模板。

不过,你说的可以实现。通过以下方式之一

方法一 (最简单)

实现holiday/pubholiday.asp,它只响应这个而不是json。

<c:forEach var="ph" items="${phList}" varStatus="PHstatus">
  <div class="row">
    <div class="col-md-4">
      <form:input path="phList[${PHstatus.index}].holidayDesc" class="form-control col-md-5" value="${ph.holidayDesc}" />
    </div>
  ...
  <br>
</c:forEach>

向数组项中添加一个容器元素,如下所示

<div id="container" >
  <c:forEach var="ph" items="${phList}" varStatus="PHstatus">
    ...
  </c:forEach>
</div>

将主页中的 ajax 请求更改为此。当您收到来自pubholiday.jsp 的响应时,请将#container 的内容替换为从 ajax 收到的内容。

...
$.ajax("holiday/pubholiday.asp?" , {
        method: "GET",
        accepts: "application/html",
        dataType: "json",
        data: $form.serialize() + '&selectedText=' + selectedText,
        success: function(response) {
            // This is where magic happens
            $("#container").html(response);   
        },
    }).done(function(data) {
        console.log(data)
        alert("Data Sent" + selectedText)
    })
...

方法二

如果您需要响应只有json,在success callback读取json,并通过连接字符串自己生成html,然后替换#container元素。

方法3 (推荐)

使用一些客户端渲染库(如聚合物或车把)将 json 渲染为 html。

【讨论】:

  • 旧的数组列表 ${phList} 仍然存在,无法用我的新数组列表替换。
  • 您采用了哪种方法。你能解释更多关于你尝试了什么,以便我可以提供帮助
猜你喜欢
  • 1970-01-01
  • 2013-12-03
  • 2016-09-03
  • 1970-01-01
  • 2011-12-22
  • 1970-01-01
  • 2017-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多