将多个ajax请求中的数据返回到页面

时间:2016-07-10 21:12:24

标签: jquery ajax

我知道这个问题的一个版本已被问到,但我找不到适用于我的解决方案。

我有一系列路由号码。我必须调用外部服务,检索与每个服务相关联的银行名称,并将它们输出到表中。 routingnum.php返回包含在routingnum函数中的bankname,如下所示:routingnum(“WELLS FARGO BANK NA”);

这是我试过的:

<script>
  function getbankname(rnum) {
    var activeurl = "https://www.example.com/php/routingnum.php?rn=" + rnum + "&callback=routingnum";
    $.ajax({
      type: "GET",
      dataType: 'jsonp',
      contentType: "application/jsonp; charset=utf-8",
      url: activeurl,
      jsonpCallback: 'routingnum',
      success: function (data) {
        var thisdiv = $("." + rnum);
        $(thisdiv).text(data);
      }
    });  
  }

  $(document).ready(function() {
    var routingnumbers = ['325070760','323075356','121042882'];
    var ddcontent = "<tbody>";
    for (var i=0; i<routingnumbers.length; i++) {
      var rnum = netPayDistributionsDetail[i];
      getbankname(rnum);
      ddcontent +="<tr><td class=" + rnum + "></td><td>" + rnum + "</td></tr>";
    }
    ddcontent += "</tbody>";

    $(ddcontent).insertAfter("#accttable thead:nth-child(1)");  

 }); 
</script>


<table width="100%" id="accttable">
  <thead>
    <tr>
      <th>Bank Name</th>
      <th class="data-format">Routing Number</th>
    </tr>
  </thead>
</table>

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我建议您将响应视为文本而不是json,并省略回调函数的使用,而是编写您自己的成功回调函数,该函数将提取银行名称,并使用路由号将其插入相应的td作为类名如下:

  function getbankname(rnum) {
        var activeurl = "https://www.example.com/php/routingnum.php?rn=" + rnum; // omit the callback function in url
    $.ajax({
      type: "GET",
      dataType: 'text', // <-- parse the data as text 
      contentType: "application/text; charset=utf-8", // <-- parse the data as text 
      url: activeurl,
      // jsonpCallback: 'routingnum', // <-- remove this, use success callback instead as shown in next line
      success: function(data) {
       // read the bank name between 'rountingnum("' and '")' using substring
       // if you have control over routingnum.php output, modify it to  just  
       // print bank name directly and omit the use of substring
         var bankName = data.substring(12, data.length - 2);
        // update the corresponding td using rnum as class selector
        $("td." + rnum).html(bankName);
      }
    });
  }


  $(document).ready(function() {
    var routingnumbers = ['325070760', '323075356', '121042882'];
    var ddcontent = "<tbody>";
    for (var i = 0; i < routingnumbers.length; i++) {
      var rnum = routingnumbers[i];
      ddcontent += "<tr><td class=" + rnum + ">loading..</td><td class='bankName'>" + rnum + "</td></tr>";
      getbankname(rnum); // schedule ajax request for current rnum, at this point the bank name will display 
                         // loading.. until the request is fulfilled and success callback defined above is executed.
    }
    ddcontent += "</tbody>";
    $(ddcontent).insertAfter("#accttable thead:nth-child(1)");

  });