且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery Ajax调用后重新加载页面

更新时间:2023-11-11 09:37:22

您似乎在发送 AJAX请求之后(可能在服务器收到并处理它之前)立即重新加载页面./p>

您可以将ajax请求存储在数组中,并且仅在所有请求都使用jquery的 when() .

function onChange() {
    var requests = [];

    jQuery('form').each(function() {
        requests.push(jQuery.ajax({
            url: "http://localhost:9001/submitStudent.do?requestType=auto",
            data: $('form').serialize(),
            type: 'POST'
        }));
    });

    jQuery.when.apply(jQuery, requests).then(location.reload, errHandler);
}

function errHandler (err) {
    // handle any errors
}

I have a jsp page which displays the details of a student .Based on the student selection from the dropdown box on change event will be fired and retrieve the min and max marks for the student.

<form name="listBean"> 
    <c:forEach var="Item" items="${listBean.nameList}" varStatus="status">
        <input type="number"name="nameList<c:outvalue='[${status.index}]'/>.initialMarks"/> 
        <input type="number" name="nameList<c:out value='[${status.index}]'/>.finalMarks"/> 
        <input type="submit" value="submit" id="submit" />
        MinMarks:<c:out value="${Item.minMarks}"/></c:if> 
        MaxMarks:<c:out value="${Item.maxMarks}"/></c:if>
     </c:forEach>
</form>

After retrieval ,updated data will be stored into the bean.Server request is handled using jquery.ajax() method

function onChange() {
    jQuery('form').each(function() {
        jQuery.ajax({
            url: "http://localhost:9001/submitStudent.do?requestType=auto",
            data: $('form').serialize(),
            type: 'POST'
          }); 
          location.reload();
    }); 
}

Once the server response is successful , i will be reloading the page so that the page will be refreshed with the bean data set during the ajax call.

But it is not displaying the data?What i am doing wrong ?

Or is there any better solution to achieve this?

Any suggestions are welcome .

Thanks

It looks like you are reloading the page immediately after sending the AJAX request, potentially before the server has received and processed it.

You could store your ajax requests in an array and only reload the page when all requests have completed using jquery's when().

function onChange() {
    var requests = [];

    jQuery('form').each(function() {
        requests.push(jQuery.ajax({
            url: "http://localhost:9001/submitStudent.do?requestType=auto",
            data: $('form').serialize(),
            type: 'POST'
        }));
    });

    jQuery.when.apply(jQuery, requests).then(location.reload, errHandler);
}

function errHandler (err) {
    // handle any errors
}