Fill a <td> with a jquery ajax call

断了今生、忘了曾经 提交于 2019-12-12 02:13:34

问题


I'm trying to make an ajax call for each of a series of 's and replace the inner html of the td with processed data from the ajax call.

As I'm locked to an ecommerce cms system my ajax call is a complete page with the following string: **!#249,00!#349,00**!#5 ltr!#**

the code below splits this to:
var pprices = ['','249,00','349,00'];
var plabels = ['','5 ltr',''];

Note: the numbers in pprices uses comma instead of full stop.

The problem is that the last line: $(this).html(endprice); fills the cell with the default value '999999' and not the new value. It seems that the line is executed before the ajax call is completed.

How do ensure that data found in the for loop is sent to the td?

My current code is this:

  $(".pricetag").each( function() {
  var pgroup = $(this).attr('group');
  var plink = "Default.aspx?ID=14&groupid=" + pgroup + "&mode=-1";
  var endprice = "999999";
  var endlabel = "";
  $.ajax({url:plink,done:function(result){
    pprices = result.split("**")[1];
    plabels = result.split("**")[2];
    prices = pprices.split("!#");
    labels = plabels.split("!#");
    for(i=0;i<prices.length;i++) { 
        j=parseInt(prices[i]); k=parseInt(endprice); 
        if(j!=0 && j<k) { endprice = prices[i]; endlabel = labels[i]; }}
  }});
  $(this).html(endprice);
  });

HTML:

<table><tr>
  <td> label </td>
  <td class="pricetag" group="<!--@Ecom:Group.ID-->"> price </td>
</tr></table>

The: <!--@Ecom:Group.ID--> fetches an id from the ecommerce system.


回答1:


Looking at the jQuery.ajax documentation, it doesn't look to me like done: is a valid setting. I think you want to use either success: or call done() on the jqXHR object returned from $.ajax().

That said, you are correct in your assumption that 'the line is executed before the ajax call is completed'... you need to move that line into your success handler function, something like:

$.ajax({url:plink,
        context: $(this),
        success:function(result){
            pprices = result.split("**")[1];
            plabels = result.split("**")[2];
            prices = pprices.split("!#");
            labels = plabels.split("!#");
            for(i=0;i<prices.length;i++) { 
                j=parseInt(prices[i]); k=parseInt(endprice); 
                if(j!=0 && j<k) { endprice = prices[i]; endlabel = labels[i]; }}
            $(this).html(endprice);
       }});

Note that I added the context setting, to pass in this from the each(), so that the success function is working with the right this.

I didn't test this. but I believe it should work. You may want to check the jQuery.ajax() docs if you have trouble.



来源:https://stackoverflow.com/questions/14856085/fill-a-td-with-a-jquery-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!