Separate json response for tags

Asked

Viewed 275 times

1

Guys, I have the following ajax call:

$(".sec-tags").html(res.data.tags);

It is returning the server call, however the call is coming as follows:

tags: "coelho,teste,gato"

Everything is coming within a single string separated by commas. How do I separate these words and place each one within an html tag:

<span class="tags">minha tag aqui</span>

My HTML is:

<div class="col-md-6">
    <div class="sec-tags">
        <span class="tags"></span>
    </div>
</div>

2 answers

2


To separate this string into pieces you can do so:

var tags = res.data.tags.split(',');

However your comment makes me believe that it is an array, but that it appears as a string when you convert to HTML with $(".tags").html(res.data.tags);.

I’ll assume it’s an array, meaning

var tags = res.data.tags; 

So to build this HTML you can do like this:

var tags = res.data.tags; // ou no caso de ser string, usa como coloquei em cima: var tags = res.data.tags.split(',');
var spans = tags.map(function(tag){
    return '<span class="tags">' + tag + '</span>';
}).join('');
$(".sec-tags").html(spans);

0

Your call is not coming with JSON, but a standard text.

use the following line:

$aux = variavel_que_recebeu_o_texto.split(",");

You will have an array and can handle your output.

  • Yes, this is only part of the result of an object. I did: var string = $(".tags"). html(res.data.tags); var resTags = string.split(","); Document.getElementByClassName("tags"). innerHTML = resTags; but no result.

  • @Hitchleonardo you need one for or the each() to iterate the elements, the split() return an array, you can use the append() to create a <span> for each element.

  • @William I thought about it, but on my console there’s an alert: "string.split is not a Function "

Browser other questions tagged

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