Estoy practicando llamadas Ajax y tengo problemas para acceder a los datos JSON devueltos.
Tengo el siguiente código a continuación
$('button').on('click', function() { $.ajax({ url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1', success: function(data) { console.log(data); }, error: function() { console.log('error occured'); }, cache: false }); });
que salidas
[ { "ID": 1127, "title": "Paul Rand", "content": "<p>Good ideas rarely come in bunches. The designer who voluntarily presents his client with a batch of layouts does so not out prolificacy, but out of uncertainty or fear. </p>\n", "link": "https://quotesondesign.com/paul-rand-7/" } ]
Solo estoy tratando de generar el content
y las propiedades del link
de mi objeto JSON. He intentado lo siguiente:
$('.message').html(JSON.stringify(data));
que salidas
[{"ID":2294,"title":"Josh Collinsworth","content":" You do not need to have a great idea before you can begin working; you need to begin working before you can have a great idea. \n","link":"https://quotesondesign.com/josh-collinsworth-3/"}]
Estoy tratando de buscar la forma estándar de manipular datos JSON, ¡gracias por toda la ayuda!
Como sugiere el nombre, stringify
convierte el JSON en una cadena. JSON es JavaScript nativo y se basa en sus datos de muestra:
[ { "ID": 1127, "title": "Paul Rand", "content": "<p>Good ideas rarely come in bunches. The designer who voluntarily presents his client with a batch of layouts does so not out prolificacy, but out of uncertainty or fear. </p>\n", "link": "https://quotesondesign.com/paul-rand-7/" } ]
obtiene una matriz (entre corchetes) de objetos (entre llaves). En este caso, es solo un objeto en la matriz, por lo que accede al primer objeto en la matriz con data[0]
y luego obtiene su propiedad de content
:
$('.message').html(data[0].content);