How to use the JSON response?

2

After a lot of trying I got to this JQUERY AJAX result, but I still can not use the JSON data, it does not work, how should I do it? Help! Thank you

The JSON response is at the end

jQuery(document).ready(function() {
    jQuery('#add-to-cart-head').submit(function() {
        var $this = jQuery(this),
            dados = $this.serialize();
        	jQuery.ajax({
            type: "POST",
			datatype: 'json',
            url: $this.attr('action'),
            data: dados,
			complete: function (mensagem) {
			$.getJSON($this.attr('action'), function(dados) {
    		for(var i=0; i<dados.length; i++) {
        
                 $('#tbody-head-cart').append
				 ('<tr class="cart-header-thumb">' +
        			'<td class="cart-head-img">' +
					'<img src="' + dados[i].image + '" alt="" title="">' +
        			'<div class="remove-add-cart-header">' +
                	'</div>' +
        			'</td>' + 
					 '<td class="cart-head-description">' +
         			 '<strong>' + dados[i].name + '</strong>' +
                      '<div>' + dados[i].tamanhos + '</div>' + '<div>' + cores + '</div>' +
        '</td>' +
       ' <td class="cart-head-price">' +
         ' <div class="strike"><strike>' + dados[i].price + '</strike></div>' +
           ' <span class="sale">' +  dados[i].saleprice + '</span>' +
             '<div class="cart-header-thmub-change">' +
             ' <input class="form-control" name="' + dados[i].cartkey + '" value="1" style="width: 50%;" type="text">' +
            '<a class="alter_qty" href="#" onclick="$(this).parents("form:first").submit(); return false;">' +
              'Alterar' +
              '</a></div><a class="alter_qty" href="#" onclick="$(this).parents("form:first").submit(); return false;">' +
            '</a>' +
                  '</td>' +
     ' </tr>');
	     	}
			});
			       
			},
			error: function(){
                alert("message");
            }
    });
	return false;
});
});
{"error":true,"message":"","total_items":1,"total":99,"cart_items":{"2099159d6749e3c101925ffc4bc24bbb":{"name":"Vestido","price":"99.00","saleprice":"89.00", "options":{"tamanhos":"p"}}}
    
asked by anonymous 06.12.2014 / 19:59

2 answers

3

Please note that your JSON is invalid. Incomplete. Missing } at the end. To verify that JSON is correct you can use the JSONLint that was developed by the JSON standard creator.

Adding } to the end of your JSON already validates and looks like this:

{
    "error": true,
    "message": "",
    "total_items": 1,
    "total": 99,
    "cart_items": {
        "2099159d6749e3c101925ffc4bc24bbb": {
            "name": "Vestido",
            "price": "99.00",
            "saleprice": "89.00",
            "options": {
                "tamanhos": "p"
            }
        }
    }
}

Then to convert to a JavaScript object you need to use the JSON.parse and assign this object to a variable.

var objeto = JSON.parse(mensagem);

In this object you can get the values of the properties you need, for example like this:

objeto.error // dá true
objeto.total // dá 99
objeto.cart_items['2099159d6749e3c101925ffc4bc24bbb'].name // dá "vestido"

Note: Properties of objects that begin with numbers can not be accessed in objeto.propriedade , they must be in parentheses: objeto['propriedade'] .

Example online: link

    
06.12.2014 / 21:14
1

Very simple friend, the response of AJAX in jQuery when requesting a JSON is a normal Javascript object. I'll use this site here for examples: link

Even you can play a little there too to get the hang of it ...

See this page: link

It will return the IP of the user who is accessing it as a JSON.

If you make a request (right here in the OS) with jQuery on the console, you will get an object with a single parameter that is the IP.

{"ip": "000.000.00.000"}

To read, just do the same thing as reading a normal object, using dot notation ( objeto.nome ) or with brackets ( objeto['nome'] );

var pessoa = {
    nome: 'Gladson',
    site: 'Stack Overflow'
};
pessoa.nome;
// ""Gladson"
pessoa.site;
// "Stack Overflow"

Run this code in the console:

$.get('http://ip.jsontest.com', function(data) {
    console.log(data);
});

It will return your IP as an object, now to get the IP value, execute this code:

$.get('http://ip.jsontest.com', function(data) {
    console.log(data.ip);
});

And that's it, it will return only the value of the IP and not the entire object.

    
06.12.2014 / 20:21