首页 > 解决方案 > Jquery ajax - 函数采用另一个函数响应

问题描述

当我在我的应用程序中同时调用多个 ajax 请求时,我遇到了非常烦人的情况(这是必要的)。我的后端响应是这样构建的:

{"one":{"id":"75068337","value":"1"},"two":{"id":"7449461","value":"1"},"events":[ ]}

但有时“事件”对象可以包含一些元素,然后它看起来像

{"one":{"id":"75095540","value":"1","re​​sult":"1"},"two":{"id":"7452784","value":"1 ","re​​sult":"1"},"events":{"1531501188":"event 1","1531501405":"event2","1531504270":"event3","1531507336":"event4"}}

现在.. 每个 ajax 调用都会被触发,这取决于是否选中了具有给定 ID 的复选框并且它调用了唯一的 url,然后在成功时它将响应值放入 html 元素中,这些元素也由它们的 ID 标识。

主要麻烦是在这里:当检查一个复选框并且他的响应给​​出带有元素的“事件”时,所有其他Ajax呼叫都将它们带入其HTML元素。

当我通过输入 ajax.php?id=1-2-3 分别检查每个响应时,后端给了我正确的响应,没有任何事件。

我的代码有什么问题?

阿贾克斯:

    var idezy = "1-2-3"; // 1-2 - values needed in backend, 3 - html element ID
    var identifier = "checkbox1"; // ID of checkbox to check if it's checked before calling ajax again

    function bier(idezy, identifier) {
        iczs = idezy.split('-');
        $.ajax({
            url: 'ajax.php?id=' + idezy,
            dataType: "json",
            success: function(results) {
                $.each(results, function(index, value) {
                    if (index == "one") {
                        $('#oneb' + value["id"]).html(value["value"]);
                        $('#onew' + value["id"]).html(value["result"]);
                    }

                    if (index == "two") {
                        $('#twob' + value["id"]).html(value["value"]);
                        $('#twow' + value["id"]).html(value["result"]);
                    }

                    if (index == "events") {
                        $.each(value, function(idx, vale) {
                            $(vale).insertBefore($('table#eventy' + iczs[2] + ' tbody#eventz' + iczs[2] + ' > tr:first'));
                        });
                    }
                });

                if ($("#" + identifier).is(':checked')) {
                    bier(idezy, identifier);
                }
            }
        });
    }
<table>
 <tbody>
  <tr>
    <td><input type="checkbox" id="checkbox1"></td>
    <td>
    <table id='eventy1'>
      <thead>
      <th>Event time</th>
      <th>Event desc.</th>
      </thead>
      <tbody id='eventz1'>
      <tr id='dummy'><td>time0</td><td>description0</td></tr>  
      </tbody>
      </table>
    </td>
  </tr>
  
  <tr>
    <td><input type="checkbox" id="checkbox2"></td>
    <td>
    <table id='eventy2'>
      <thead>
      <th>Event time</th>
      <th>Event desc.</th>
      </thead>
      <tbody id='eventz2'>
      <tr id='dummy'><td>time0</td><td>description0</td></tr>  
      </tbody>
      </table>
    </td>
  </tr>
  
  <tr>
    <td><input type="checkbox" id="checkbox3"></td>
    <td>
    <table id='eventy3'>
      <thead>
      <th>Event time</th>
      <th>Event desc.</th>
      </thead>
      <tbody id='eventz3'>
      <tr id='dummy'><td>time0</td><td>description0</td></tr>  
      </tbody>
      </table>
    </td>
  </tr>

 </tbody>
</table>

标签: jqueryajax

解决方案


推荐阅读