简体   繁体   中英

jquery using json object

script.js

$('#loginform').submit(function(e){
    $.ajax({
        type:"POST",
        url:"/accounts/login/ajax/",
        data:$('#loginform').serialize(),
        success: function(msg){
            var msg = msg;
            msg = JSON.parse(msg);
            $('#messagestatus').html('');
            if(msg.username != null){
                $('#messagestatus').append(msg.username);
            }
            if(msg.password != null){
                $('#messagestatus').append(msg.password);
            }
        }
    });
    e.preventDefault();             
});

returned object

{'username':['Required'],'password':['Required']}

When I am using JSON.parse and I am alerting, it's showing the correct error, but when I am appending it to the messagestatus div its not responding, please help .

Your username and password are arrays in your json.Either make it that your json looks like

    {'username':'Required','password':'Required'}

or change your script:

    if(msg.username.length > 0)
    {
       $('#messagestatus').text(msg.username[0]);
    }
    if(msg.password.length > 0)
    {
       $('#messagestatus').text(msg.password[0]);
    }

Might be significant, might not be, but your json object actually consists of sub-arrays:

{'username':['Required'],'password':['Required']}
            ^----------^            ^----------^

meaning that the decoded data structure in JS would actually be

obj['username'][0]   and        obj['password'][0]

First of all, parameters do not need to be redeclared in their function.

then, to parse your json using $.parseJSON() :

msg = $.parseJSON(msg);

Your JSON contains arrays, use msg["username"][0] to access the first string and not the full array.

And I would put e.preventDefault(); as first statement before AJAX.

And .html('') => .empty() but it's the same result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM