简体   繁体   English

JavaScript 包括方法

[英]JavaScript Includes Method

Could someone take a look at this and help me out?有人可以看看这个并帮助我吗? I've been working on it for a little while now and can't figure out what I'm missing.我已经研究了一段时间,无法弄清楚我错过了什么。

I'm trying to set the inner HTML of a DOM element based upon the presence of a code within the message value of this response object我正在尝试根据此响应 object 的消息值中是否存在代码来设置 DOM 元素的内部 HTML

{
  error: "{\"code\":-1121,\"msg\":\"Invalid symbol.\"}"
  message: "400 - \"{\\\"code\\\":-1121,\\\"msg\\\":\\\"Invalid symbol.\\\"}\""
  name: "StatusCodeError"
  statusCode: 400
}

 const data = await res.json(); if (data.statusCode == 400) { let parsedData = data.toString(); if (parsedData.includes('1121')) { statusMessage.className = 'alert alert-danger text-center err-message'; statusMessage.innerHTML = 'Invalid symbol.' } }

data.error is JSON, you should parse it and then check the code property. data.error是 JSON,你应该解析它然后检查code属性。

 const data = await res.json(); if (data.statusCode == 400) { let error = JSON.parse(data.error); if (error.code == -1121) { statusMessage.className = 'alert alert-danger text-center err-message'; statusMessage.innerHTML = error.msg; } }

Before you parsed the data transform it to JSON format.在解析数据之前,将其转换为 JSON 格式。

let parsedData = JSON.parse(data.error);

Check for a specific property code by using dot notation使用点符号检查特定的属性code

if(parsedData.code === -1121))

The parsedData checked should be the message not the whole data检查的 parsedData 应该是消息而不是整个数据

 var data={ error: "{\"code\":-1121,\"msg\":\"Invalid symbol.\"}", message: "400 - \"{\\\"code\\\":-1121,\\\"msg\\\":\\\"Invalid symbol.\\\"}\"", name: "StatusCodeError", statusCode: 400, } if (data.statusCode == 400) { let parsedData = data.message.toString(); if (parsedData.includes('1121')) { console.log('alert alert-danger text-center err-message'); console.log('Invalid symbol.')} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM