Two common solutions for getting JSON undefined issues at the foreground

Source: Internet
Author: User

A friend from the blog Park answers:

Why to Eval here to add "(" ("+data+");//"?

The reason is that eval itself is a problem. Since JSON is started and ended in the way "{}", in JS, it will be

is treated as a block of statements, so it must be coerced into an expression.

The purpose of the parentheses is to force the Eval function to force the expression in parentheses when it is handling JavaScript code

(expression) is converted to an object instead of being executed as a statement (statement). Give an example, for example, to

Like literal {}, if no outer brackets are added, Eval will recognize the braces as the beginning of the JavaScript code block and

End tag, then {} will be considered an empty statement executed. So the following two execution results are different:


Alert (eval ("{}");//return undefined


Alert (eval ("({})");//return Object[object]

For this kind of writing, in JS, you can see everywhere.

such as: (function ()) {} (); Do the closure operation and so on.

Note: The framework used for this example is Spring+springmvc+mybatis Plus

MyBatis Plus is an enhanced version of the existing MyBatis
Official website: http://mp.baomidou.com

Here is a more detailed introduction

Code generator can refer to: everyone open source http://www.renren.io/

The above open source framework is a great help to improve development efficiency.

Example of login verification (success example):

/** * Login js */$ (function () {    $ ("#btn_login"). Click (function () {        var mobile = $ ("#mobile"). Val ();        var password = $ ("#pwd"). Val ();        Alert (mobile+ "| |" +password)        $.ajax ({            URL: "/lms/user/login",            Type: "POST",            data: {"mobile": Mobile, "password": Password},            dataType: ' json ',            success:function (data) {                var json = eval ("(" +data+ ")");             if (json.returncode== "111111") {                 alert (json.returnmsg);             } else if (json.returncode== "222222") {                 alert (json.returnmsg);             } else if (json.returncode== "000000") {                 alert (json.returnmsg);             } else{                                  alert ("with exception, please contact the Administrator");             }                },error:function () {                alert ("error");        });});});

@RestController @requestmapping ("/USER") Public classUsercontroller {Private StaticLogger Logger = Logger.getlogger (Usercontroller.class); @AutowiredPrivateUserService UserService; @AutowiredPrivateUserauthsservice Userauthsservice; @RequestMapping (Value= "/login", method=requestmethod.post,produces= "Application/json;charset-utf8") @ResponseBody Publicstring Login (string mobile,string password) {logger.info ("User phone Number:" +mobile); Logger.info ("User password:" +password); Entitywrapper<UserEntity> wrapper =NewEntitywrapper<userentity>(); Wrapper.eq ("Mobile", mobile); Userentity User=Userservice.selectone (wrapper); Entitywrapper<UserAuthsEntity> Wrapper2 =NewEntitywrapper<userauthsentity>(); Wrapper2.eq ("Identifier", User.getmobile ()); Userauthsentity Userauth=Userauthsservice.selectone (WRAPPER2); Logger.info ("Userentity:" +user.getmobile ()); Logger.info ("Userauth:" +userauth.getcredential ()); Map<String,Object> map =NewHashmap<string,object>(); if(!userauth.getidentifier (). Equals (MOBILE) {Map.put ("ReturnCode", "111111"); Map.put ("Returnmsg", "Phone number wrong"); }Else if(!userauth.getcredential (). Equals (password)) {Map.put ("ReturnCode", "222222"); Map.put ("Returnmsg", "Bad password"); }Else{map.put ("ReturnCode", "000000"); Map.put ("Returnmsg", "Pass Validation"); Map.put ("User", user); Map.put ("Userauth", Userauth); }              returnjson.tojsonstring (map); }}

Failure Example:

/** * Login js */$ (function () {    $ ("#btn_login"). Click (function () {        var mobile = $ ("#mobile"). Val ();        var password = $ ("#pwd"). Val ();        Alert (mobile+ "| |" +password)        $.ajax ({            URL: "/lms/user/login",            Type: "POST",            data: {"mobile": Mobile, "password": Password},            dataType: ' json ',            success:function (data) {                             if (data.returncode== "111111") {                 alert ( data.returnmsg);             } else if (data.returncode== "222222") {                 alert (data.returnmsg);             } else if (data.returncode== "000000") {                 alert (data.returnmsg);             } else{                                  alert ("with exception, please contact the Administrator");             }                },error:function () {                alert ("error");        });});});

Two examples that can successfully return JSON data, while the latter returns undefined

And when you remove the returnmsg,returncode behind the data.returnmsg or Data.returncode, the direct alert (data) is the one that can return

The returned data is directly from the JSON string ({} in the form of JSON strings), and the JSON is not formatted, so fetching the data directly leads to undefined

There are two ways of formatting JSON:

Way One:

One is the above var json = eval ("(" +data+ ")"); Called using Eval to parse

Way two:

var json = "{User: ' User '}"

var obj = new Function ("return" +json)//converted JSON object

alert (obj.name);

alert (obj.age);

Two common solutions for getting JSON undefined issues at the foreground

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.