简体   繁体   中英

How to get object from data returned from Ajax call in jQuery?

I have this ajax code:

$.ajax({
    type: "POST",
    url: "inc/ajax.php",
    data: $('#form-responder').serialize(),
    success: function (data) {
        console.log(data); // prints: {"sucesso":"true", "mensagem":"Correta: A pulseira de identificação se aplica a todos os pacientes, sem exceção. ", "index_proxima":"2"}
        //var sucesso = eval(data.sucesso);
        var mensagem = data.mensagem;
        alert(mensagem); // shows: undefined
    }
});

I need to get some object values but all of them are returning 'undefined', what is wrong with that? I used to do data.something and always worked before, maybe something with this jQuery version 2.1.3 ?

You need to use parseJson()

JsFiddle

data = jQuery.parseJSON( data);
alert(data.mensagem);

"mensagem" is string key, you should use it with array key format like so: data['mensagem'] .

 var data = {"sucesso":"true", "mensagem":"Correta: A pulseira de identificação se aplica a todos os pacientes, sem exceção. ", "index_proxima":"2"}; $('input').val(data['mensagem']); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <input /> 

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