我有一个AJAX调用,它得到一些字符串,例如:
9315554e54
,但事实是当它们应解释为纯字符串响应时,它们被解释为数字931555.4e+54
。
这是代码:
return axios.post('getPath', {id_path: id_path}).then((r) => {
console.log(r.data); // would give something like 931555.4e+54 when it should be 9315554e54
// tried this which would not work since it will be incremented by 1 due to the mathematic notation : (9315554e55)
console.log(r.data.replace(/(\+|\.)/g, ''))
}).catch(function (error) {
console.log(error);
});
我能得到一个字符串吗?
答案 0 :(得分:3)
axios
库解析响应using JSON.parse
by default。这是配置的transformResponse
参数的一部分。
如果您的响应是纯字符串,则此函数将尝试将其解释为JSON。
var parsed = JSON.parse('9315554e54');
window.document.write(parsed, ' ', typeof(parsed));
然后解决方案是覆盖此默认行为:
return axios.post('getPath', {id_path: id_path}, {
transformResponse: (data) => data,
}).then((r) => {
console.log(r.data);
}
或更简洁
return axios.post('getPath', {id_path: id_path}, {
transformResponse: null,
}).then((r) => {
console.log(r.data);
}