【问题标题】:How to check for empty json response with regex in javascript?如何在javascript中使用正则表达式检查空的json响应?
【发布时间】:2023-03-28 02:37:01
【问题描述】:

我的 ajax 响应返回一个空响应(即带有多行空格),我想在我的成功函数中检查它。如何在 javascript 中使用正则表达式检查空 json 响应?

【问题讨论】:

  • 你能举一个这样的回应的例子吗?它是否包含属性?

标签: javascript regex json


【解决方案1】:
> /^\s*$/.test("foo")
false
> /^\s*$/.test("")
true
> /^\s*$/.test("   ")
true
> /^\s*$/.test("\n\n")
true

【讨论】:

  • +1 特别适用于使用regex.test 而不是string.match
【解决方案2】:
  1. jQuery.ajax 数据类型设置为text
  2. 创建以下success回调

    $.ajax({
      // other options..
      dataType: 'text',
      success(planinTextData) {
        if (planinTextData !== '') {
          var data = JSON.parse(planinTextData);
        }
      }
    });
    

【讨论】:

  • -1 OP特别提到了“多行空格”,这错过了。 (P.S. 列表项内的代码缩进八个空格。)
猜你喜欢
  • 2012-07-27
  • 2011-01-16
  • 2016-06-29
  • 1970-01-01
  • 2021-12-06
  • 2019-08-01
  • 2019-06-23
  • 1970-01-01
相关资源
最近更新 更多