How to use JSON response?

Asked

Viewed 977 times

2

After a lot of trying I arrived at this result of JQUERY AJAX, but I still could not use the JSON data, they do not work, how should I do ? give a Help ! thank you

The JSON response ta 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"}}}

2 answers

3


Note that your JSON is invalid. Incomplete. Missing } at the end. To verify that JSON is correct you can use Jsonlint which was developed by the creator of the JSON standard.

Adding } at the end of your JSON already validates right and gets this look:

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

There to convert to a Javascript object you need to use the JSON.parse and assign that object to a variable.

var objeto = JSON.parse(mensagem);

In this object you can fetch 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 starting with numbers cannot be accessed in the way objeto.propriedade, have to be with straight parentheses: objeto['propriedade'].

Online example: http://jsfiddle.net/8Lwdfsc0/

1

Very simple friend, the answer of AJAX in the jQuery when ordering a JSON is a normal Javascript object. I will use this site here for the examples: http://www.jsontest.com

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

See this page: http://ip.jsontest.com

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

If you make a request (right here from 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 way you would read a normal object, using point 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 on 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, run this code:

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

And ready, it will return only the value of the IP and not the complete object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.