后端传的“alert”字符串 html页面变成了alert_a_l_e_r_t
时间: 2023-08-01 18:15:16 浏览: 51
这种情况通常是因为传递的字符串被浏览器解析为了HTML实体字符。其中,字母a、l、e、r、t分别对应HTML实体字符中的“&a;”、“&l;”、“&e;”、“&r;”、“&t;”。
要解决这个问题,可以使用JavaScript中的unescape()函数或使用jQuery中的html()函数来解码HTML实体字符。具体方法如下:
1. 使用unescape()函数解码HTML实体字符:
```javascript
var str = "alert_a_l_e_r_t";
var decodedStr = unescape(str.replace(/_/g, '%'));
alert(decodedStr); //弹出"alert"
```
2. 使用jQuery的html()函数解码HTML实体字符:
```javascript
var str = "alert_a_l_e_r_t";
var decodedStr = $('<div/>').html(str).text();
alert(decodedStr); //弹出"alert"
```
以上两种方法都可以把字符串中的HTML实体字符解码成正常字符。
相关问题
后端传的“alert”字符串 html页面变成了alert_a_l_e_r_t 如何让页面与后端传来的参数一致
要解决这个问题,可以在前端对传递过来的字符串进行解码,具体方法如下:
```javascript
var str = "alert_a_l_e_r_t";
var decodedStr = str.replace(/_[a-z]_/g, function(match) {
return String.fromCharCode(parseInt(match.slice(1, -1), 36));
});
console.log(decodedStr); //输出"alert"
```
上述代码中,使用正则表达式匹配字符串中所有的“_a_”、“_l_”、“_e_”、“_r_”、“_t_”格式的字符串,并使用String.fromCharCode()函数将其转换成对应的字符,最终得到解码后的字符串。
js接收后端返回的flask字符串例子
好的,以下是一个基本的在前端使用JavaScript接收后端返回的Flask字符串的例子:
```javascript
// 假设后端使用 Flask 返回一个 JSON 格式的数据,其中有一个 key 是 "message",对应的 value 是一个字符串
fetch('/api/endpoint')
.then(response => response.json())
.then(data => {
console.log(data.message) // 输出后端返回的字符串数据
})
.catch(error => console.error(error));
```
在上面的代码中,我们使用了 Fetch API 来获取后端返回的数据。其中 `/api/endpoint` 是一个示意的 API 路径,你需要根据实际情况修改。
当后端返回数据后,我们调用 `response.json()` 将响应转化为 JSON 格式,然后在 `then()` 包裹的回调函数中获取数据并输出。
注意,要在控制台中查看数据,你需要使用 `console.log()` 函数,而不是 `alert()` 函数。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)