If your return is a list of objects:
[
{subcategoria: "Artesanato"},
{subcategoria: "Esculturas"},
{subcategoria: "Ferramentas"},
{subcategoria: "Livros"}
];
It does not make sense for you to interact with the subcategoria
property, since it only exists in elements belonging to the list, as you did in:
$.each(retorno.subcategoria, function(i, val){
var subcategoria = '<option value="'+retorno.subcategoria[i].subcategoria+'">'+retorno.subcategoria[i].subcategoria+'</option>';
$("select[name=subcategoria]").html(subcategoria);
});
Correct is to break in on the return itself and access the subcategoria
property of the present value in the list:
$.each(retorno, function(i, val) {
// -----------^
var subcategoria = '<option value="'+val.subcategoria+'">'+val.subcategoria+'</option>';
// ----------------------------------^ --------------^ ----^ --------------^
$("select[name=subcategoria]").append(subcategoria);
// ----------------------------^
});
Note : Comments entered in the code in the format ---^
indicate the points where the changes occurred relative to the original code and therefore deserve more attention.
Note also that it is necessary to replace the html
method with append
, since the first always overrides the current value and, if used, only the last subcategory of the list would appear. In order to appear all, the append
method is used, which only inserts the new value at the end of the current value.
Example
const RETORNO = '[{"subcategoria": "Artesanato"},{"subcategoria": "Esculturas"},{"subcategoria": "Ferramentas"},{"subcategoria": "Livros"}]';
$(() => {
var list = $("#list");
$.each(JSON.parse(RETORNO), (key, value) => {
//-----^ Aqui você converte seu retorno, que é uma string, para objeto
let option = "<li>" + value.subcategoria + "</li>";
list.append(option);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ulid="list"></ul>