多次运行$ .ajax() [英] Running $.ajax() Multiple Times
问题描述
我有一个jQuery $ .ajax()函数,成功返回一个base64值(即pdf页).我必须返回多个base64值,因此我想到的唯一方法是遍历$ .ajax()函数.当返回每个成功时,我将base64值写入一个image元素.这很好.问题是,因为它是异步的,所以不一定按顺序返回页面. 我知道这不是最好的方法,但是如果我总是要有一个不同的值(页数),该如何链接它?
I have a jQuery $.ajax() function that is returning a base64 value's, which are pdf pages, on success. I have to return multiple base64 values, so the only way that I could think of how to do this, is to loop through the $.ajax() function. When each success is returned, I write the base64 value into an image element. This works fine. The problem is, because it is asynchronous, it does not necessarily return the pages in order. I understand that it isn't the best method, but how can I chain this if I am always going to have a different value, which is the page count?
for (i = 1; i <= pdfPageCount; i++) {
$.ajax({
type: 'POST',
contentType: 'application/json',
url: 'Page.aspx/Method',
dataType: 'json',
error: function (err) {
alert('Error: ' + err);
},
success: function (resultStr) {
//alert('Page: ' + i);
var sigImage = document.createElement("img");
sigImage.setAttribute('src', 'data:image/png;base64,' +
resultStr.d);
document.getElementById("imgId").appendChild(sigImage);
},
});
} // end the for loop
HTML只是有一个div:
The HTML just has a div:
<form id="form1" runat="server">
<div id="imgId">
</div>
</form>
推荐答案
它们的关键是使用何时.虽然您可以以同步方式链接呼叫,但我不建议这样做.更好的方法是异步调用每个页面,然后同时等待所有结果.
They key is to use when. While you can chain your calls in a synchronous manner, I wouldn't suggest it. A better approach would be to asynchronously call for each page, then await all the results simultaneously.
var pages = [];
var deferredObjs = [];
for (i = 0; i <= pdfPageCount; i++) {
deferredObjs[i] = $.ajax({
type: 'POST',
contentType: 'application/json',
url: 'Page.aspx/Method',
dataType: 'json',
error: function (err) {
alert('Error: ' + err);
},
success: function (resultStr) {
pages[i] = resultStr;
},
});
} // end the for loop
$.when.apply( $, deferredObjs ).then( aFunctionToProcessPageResults() );
此外,您的POST不应提供要返回的页码吗?请注意,我将索引变量更改为以0开头.您可能需要对此进行说明.
Also, shouldn't your POST be supplying the page number to return? Note that I changed your index variable to start a 0. You may need to account for this.
这篇关于多次运行$ .ajax()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!