【问题标题】:Check Ajax success response before printing it out在打印出来之前检查 Ajax 成功响应
【发布时间】:2021-12-29 19:09:27
【问题描述】:

我从 Ajax 调用中获得了一些带有 div 块的 html 代码。我想在这个 html 上建立一个 if/else 检查,更具体地说是在返回的 div 的 id 属性上。如果它小于或大于 10,我会打印不同的结果。

ajax调用返回的html:

    <div id="10" class="names">Text</div>
    <div id="2" class="names">Text</div>
    <div id="10" class="names">Text</div>
    <div id="11" class="names">Text</div>

Ajax 调用

$.ajax({
  type: "POST",
  url: "https://example.com/api",
  data: data,
  cache: false,
  success: function(html) {
    //check html response for the id attribute, print html after the check 
  },
  error: {}
});

知道怎么做吗?

【问题讨论】:

    标签: javascript jquery ajax


    【解决方案1】:

    这样的?

    注意你有两个 id="10"

    const html = `<div id="10" class="names">Text</div>
    <div id="2" class="names">Text</div>
    <div id="10" class="names">Text</div>
    <div id="11" class="names">Text</div>`
    
    function success(html) {
        //check html response for the id attribute, print html after the check 
       const res = $("#content").html(html)
       .find("div")
       .map(function() {
         return $(this).attr("id")
       }).get();
       console.log(res,res.includes('10') ? 'has id 10' : 'does not have id 10')
    }
    
    success(html)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <div id="content"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 2013-08-26
      • 1970-01-01
      • 1970-01-01
      • 2018-12-13
      • 1970-01-01
      • 2013-05-03
      相关资源
      最近更新 更多