Recently, when using the Ajax method of jquery to receive JSON data, there is a problem, that is, the data returned, sometimes can be used directly as JSON data, but sometimes not.
After the Netizen pointed out, this question already has the relatively clear conclusion, that is the jquery Ajax method The complete method is not processing datatype, therefore if you are in complete inside attempts directly to use the JSON data is not feasible, must first pass the eval.
The $.ajax method is as follows:
Java code $.ajax ({type: "POST", url:ctxroot+ ' folderaction!saveinformsetting.action ', data: ' jsonstr= ' + inform_ SETTINGLISTSTR, DataType: "JSON", complete:function (data) {///doing something here, assuming that the returned JSON data has the name attribute//can sometimes be directly data.name or data [' name '] to access//But sometimes it is through var jsondata = eval ("(" +data.responsetext+ ")"); can only be accessed through jsondata.name, and in this case, complete rather than success}} is required;
OK, the problem has been explained in the code comments, the following are the two different reasons.
Let's start by stating the first case:
I have found that the server-side code must be a constant string of direct renturn when the data is accessed directly from the property name. What is a constant string, some people may not be very clear, the constant string refers to a string directly "", there is no definition of string variables directly put a string "" Print to the foreground, It can be accessed directly by the Data property name, and the jquery end can be obtained only if it is written success.
The following are the causes of the eval and the inability to enter success:
This is because the server side print is a string object, usually this kind of problem in my code because the background JSON is more complex, in the organization when I used the StringBuffer, Then the last print is the StringBuffer object's ToString, so it's equivalent to print a string object
In this case, the Ajax method of jquery will not enter the success method, can only be received with complete, and want to parse data in the JSON, the Data.responsetext must be eval
In addition to these two points, it is also important to note that if you are using jq1.4, then he has more stringent requirements for the format of the JSON, all the keys and attributes should be in double quotation marks, although the key does not use double quotes native JS is allowed, but jq1.4 seems to have this requirement.
Jquery JavaScript parses the JSON data returned by Ajax (GO)