$ .get()在提交页面之前遇到麻烦

时间:2011-05-23 12:37:36

标签: javascript jquery

想一个带有“商品”的购物篮。 我有一个<li>元素列表,每个元素都有一个包含数字的字段 - 金额。

从概念上讲,这就是我想要的:当用户按下按钮时,我会遍历每个选择金额的<li>元素。然后我做一个$ .Get()来调用服务器的商品ID +金额来检查商店是否有足够的特定商品。服务器回复True og False。 此回复临时存储在html字段中。 循环结束后,我检查是否有任何商品的错误回复。 如果是这样,我突出显示“虚假”项目。或者我只是提交。

好的,问题是我的代码接缝继续通过我的$ .get()回调函数,所以在$ .get()实际收到结果之前评估是否返回任何false的最终检查从服务器。 无论如何,这就是我认为正在发生的事情......

现在让我们看看一些代码:

var tmp = new Array();
var id = '';
var c = '';
var n = 0;
var z=0;
$('#basket').find('li.list').each(function() {
c = $(this).find('input.fldamount').val();  // this is the amount field
id = $(this).attr('id');  // this is the id no of the item
$.get('./(RPC)?OpenAgent&cmd=movewhcheckamount&unid='+id+'&count='+c, function(data) {
    $('#RPCResult').val(data);  // i store the returned value in a html field
    if ( $('#RPCResult').val() == "true" ) {
      tmp.push( id+'|'+c );  // if true is returned, i push the id & amount to an array
    } else {
      $(this).addClass('red');  // else i tag the item
      n=n+1;  // and then increment a counter
    }
} );  // $('#basket')

var t = window.setTimeout( function() {
  if (tmp.length > 0 && n == 0)  {  // if i got items in the array AND my false counter is zero
    $('#SelectedArtikler').val( tmp.join(";") );  // then i store the array as text in a field
    document._FlyttArtikel.submit();  // and submit
  } else if (n > 0) {
    // show a popup
    alert("You're trying to move more items than exists...");
  } else {
    alert("ops, nothing to move...");  // should never end up here...
  }
}, 1000);
window.clearTimeout(t);

正如你所看到的,我试图使用setTimeout来反击通过我的回调函数运行的代码,这样我基本上等待一段时间让服务器有时间做出响应。 我确实在setTimeout周围有另一个循环,只要我的#RPCResult字段为空,就会继续循环,但这会导致无限循环。

我有#RPCResult字段可见所以我可以看到发生了什么,我看到的是弹出窗口“你正在尝试移动更多的项目...”显示和RIGTH我按下确定弹出窗口然后#RPCResult字段获得结果true / false。

我现在可以对一些代码进行优化,但我现在感兴趣的是以正确的方式获得$ .get()结果。

提前致谢; - )

1 个答案:

答案 0 :(得分:0)

当所有“$ .get()”调用完成内部回调例程时,您将不得不放置将要运行的代码。这是唯一可以确定您实际获得服务器响应的地方。保持计数器返回的次数,当计数器增加到等于项目总数时,您就知道所有响应都可用。

因此:

var basketSize = $('#basket').find('li.list').length, completed = 0;

为您提供项目数并初始化计数器。在传递给“$ .get()”的回调函数中,您可以执行以下操作:

  if (++completed === basketSize) {
    // code currently in the "setTimeout()" callback
  }

您的代码似乎已经完成了一些工作(您递增的“n”变量)。

现在,我说过,我还会注意到为每个“项目”执行单独的HTTP事务是非常疯狂的。您应该将它们全部捆绑到一个 HTTP请求中,该请求将返回一个答案列表。

此外,将响应存储在“RPCresult”字段中的“$ .get()”中毫无意义;只是检查“数据”的价值,因为无论如何都没有再看过“RPCresult”。