如何循环ajax请求(使用jquery)和jsp

How do i loop an ajax request (using jquery) and jsp

本文关键字:使用 jquery jsp 请求 ajax 循环 何循环      更新时间:2023-09-26
<script>
//when page is ready do the following
$(document).ready(function()
{
    //set interval of refresh
    setInterval(doAjaxMethod, 1000);
});
function doAjaxMethod(id)
{ 
     $.ajax({
        url: "getStatus/"+id,
        dataType: "json",
        success: function(json)
        {
            $('#ajaxStatus').html(json.status);
        }    
});
</script>
<%
   //How can I do something like this
    int n = object.size();
    for(int i=0; i<n; i++)
    {
         doAjaxMethod(object.getId());
    } 
%>
<div id=ajaxStatus> status updates here </div>

我不会在scrippets中混合调用javascript。相反,用javascript管理循环。如果你描述更多你想做的事情,我可以更具体一些。jsp上似乎有一个可用的容器对象,您需要循环通过以获取容器中内容的状态。与其将该对象传递给jsp,不如创建一个端点,让jsp上的javascript可以在ajax中调用该端点来获取所需的所有数据。

可以做的一种方法是用css类将它们添加到类似列表的对象中,并在其上触发ajax方法onLoad。这是一些未经测试(可能是未编译)的

<%
   //How can I do something like this
    int n = object.size();
    for(int i=0; i<n; i++)
    {
         out.println("<li class='abcd' id ='<%=object.getId()%>'>" +object.getId() +"</li>");
    } 
%>

然后在javascript页面加载

$(function(){
    $('.abc').each(i, v){
                doAjaxMethod($(v).attr('id'));
    }
});

试试这个(假设objArray是一个数组):

$.each(objArray, function(i, obj) {
       doAjaxMethod(obj.getId());
});

它将迭代您的数组,obj是每个项。希望能有所帮助。