This article mainly introduces how to solve the wx.request processing exception for JSON containing \u2028 in the WeChat applet. It has certain reference value. Now I share it with you. Friends in need can refer to it
Recently, during the development process of the mini program, I encountered a magical problem.
The API wx.request used by the applet to initiate network requests will parse the response body in JSON format by default and return a JS Object.
wx.request({ url: 'test.php', //仅为示例,并非真实的接口地址 data: { x: '', y: '' }, header: { 'content-type': 'application/json' // 默认值 }, success: function(res) { console.log(res.data) } })
Among them, res.data
will generally be of Object type.
However, if the JSON data of the response body contains the characters \\u2028
, the interpretation will fail, and the output res.data
is the string type of the response body. .
Test sample:{"test":"There is a special character here: "}
Test code:
wx.request({ ... success: (res) => { console.log('APIFactory:run', '调试', { res }); }, });
Result:
can be parsed normally in the developer tools
on the real machine ( iOS and Android), both parsing failed
\u2028, parsing is the line separator.
This character is compatible in JSON strings and can be parsed normally by
JSON.parse.
But if there is this string in the JS code, it will cause a running error.
The JS script execution environments of the three terminals are different:
wx.request For the data processing of the response body, is it processed by JS Engine or Native? Since WeChat does not disclose the source code of the mini program, it is unknown. The processing of
wx.request is equivalent to a black box for us, and there are many possible values for the data type of
res.data. If you want To provide better robustness in business, it also needs to be compatible with the judgment and fault-tolerant code when
res.data is of
Object/String type.
Explanation of tips for Array arrays in JavaScript
The above is the detailed content of How to solve the processing exception of wx.request for JSON containing \u2028 in the WeChat applet. For more information, please follow other related articles on the PHP Chinese website!