The usual approach is var jsonData = eval(xmlHttp.responseText). This may seem like everything is correct, but when you run the code, you'll find an "invalid label" error. Why? I don't know either, but I found a way to solve this problem.
It was also a headache when I first encountered this problem, because it seemed that all the coding was correct. In order to test where the problem occurred, I gradually narrowed down the code scope, and finally got the following short code:
var jsonStr1 = '{"Name":"Tom","Sex ":"Man"}';
var jsonObj1 = eval(jsonStr1);
alert(jsonObj1.Name);
The execution of the above code is exactly what the invalid labe said at the beginning mistake. Does the eval function have restrictions on certain expressions or objects? So I tested the array object again, the code is as follows, and the result is that the following code runs normally:
var arrStr = '["Tom","Man"]';
var arrObj = eval(arrStr);
alert(arrObj[0]);
Could it be that the JavaScript parser on my machine has a problem with JSON parsing, so I tested the following code again, but the result was still normal:
var jsonObj = {"Name":"Tom","Sex":"Man"};
alert(jsonObj.Name);
In the end, I still didn’t solve the problem by myself, so I searched the Internet for answers based on the relevant error messages. Unexpectedly, I found the root of the problem all of a sudden. The solution was “When eval, you must first JSON string values are enclosed in '()' brackets first." The information I found online didn't explain the reason, and of course I still didn't understand the real reason. Parentheses are used to force execution or calculation first. The returned JSON is a complete object with no expressions in the middle. Why do we need to add parentheses! More complex objects like arrays can also be eval normally. There is no other way, just remember this usage first. The correct usage is as follows (pay attention to the brackets at both ends of eval):
var jsonStr2 = '{"Name":"Tom","Sex":"Man"}';
var jsonObj2 = eval('(' jsonStr2 ')');
alert(jsonObj2.Name);