During Ajax application development, we usually like to use the JSON format string returned by the server as JavaScript in the callback function of the client.CodeRun the command and save it with a variable to facilitate the use of the returned data. The common practice is Var jsondata = eval (XMLHTTP. responsetext ). It seems that everything is correct, but when you run the code, you will find the "invalid Labe" error. Why? I don't know, but I found a solution to this problem.
I also had a headache when I first encountered this problem, because it seems that all the codes are correct. To test the problem location, I gradually reduced the scope of the code and finally got the following brief code:
VaR Jsonstr1 = ' {"Name": "Tom", "sex": "Man "} ' ;
VaR Jsonobj1 = Eval (jsonstr1 );
Alert (jsonobj1.name );
The preceding code execution reports the invalid Labe error. Does the eval function have restrictions on some expressions or objects? So I tested the array object again. The Code is as follows. The following code runs normally:
VaR Arrstr = ' ["Tom", "man"] ' ;
VaR Arrobj = Eval (arrstr );
Alert (arrobj [ 0 ]);
Is it because the Javascript parser on my machine has a problem with JSON parsing, so I tested the following code, but the result is the same as normal:
VaR Jsonobj = { " Name " : " Tom " , " Sex " : " Man " };
Alert (jsonobj. Name );
In the end, I still did not solve the problem by myself, so I searched for the answer based on the relevant error information. I did not expect to find the root cause of the problem at once. The solution is"When Eval is used, you must enclose the JSON string value in brackets". None of the materials found on the internet indicate the reason. Of course, I still do not understand the reason. Parentheses are mandatory for execution or calculation. The returned JSON is a complete object without an expression in the middle. Why do we need to add parentheses! Objects with complex points such as Arrays can also run eval normally. No way. Remember this usage first. The correct usage is as follows (check the brackets at both ends of eval ):
VaR Jsonstr2 = ' {"Name": "Tom", "sex": "Man "} ' ;
VaR Jsonobj2 = Eval ( ' ( ' + Jsonstr2 + ' ) ' );
Alert (jsonobj2.name );