How to convert a string to object in JavaScript?

1

I have this code:

<html><head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="robots" content="noindex, nofollow">
  <meta name="googlebot" content="noindex, nofollow">
  <script type="text/javascript" src="//code.jquery.com/jquery-1.6.2.js"></script>
  <link rel="stylesheet" type="text/css" href="/css/normalize.css">
  <link rel="stylesheet" type="text/css" href="/css/result-light.css">
  <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.14/jquery-ui.min.js"></script><linkrel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.14/themes/black-tie/jquery-ui.css">
  <title>jQueryUI 1.8.14 Autocomplete</title>
  <script type="text/javascript">


function montaAutocomplete(source) {
  
  var dados = [{ label: "Agostinho", value: "1" }];
  //DADOS: VARIÁVEL ESTÁTICA
  document.getElementById('resultado').innerHTML = dados;

  //SOURCE: VEM DO BANCO DE DADOS
  document.getElementById('resultado1').innerHTML = source;

    $("#descricao").autocomplete({
        source: dados,
        minLength: 1, //quantidade de caracteres para começar a buscar
        select: function (event, ui) {
            //evento de quando você seleciona uma opção        
            $("#descricao").val(ui.item.label);
            $("#id").val(ui.item.value);
            event.preventDefault();
        }
    });
   
}

function busca(x){

  $.ajax({
    type:"GET",
    url: "autocomplete.php?q=" + x,
    dataType:'text',
    success : function(data) {
        montaAutocomplete(data);
      }
    });

}






</script>
</head>
<body>
  <input type="text" id="descricao" onkeyup="busca(this.value);" class="ui-autocomplete-input" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
<input type="text" name="id" id="id">
<br>
dados:<br><div id="resultado"></div>
<br>
source:<br>
<div id="resultado1"></div>

It is an application with the autocomplete feature which communicates with the file autocomplete.php which, from the keys entered by the user, it returns the following code:

Example, if the user types in the input the name agostinho , autocomplete will return

  

[{label: "Augustine", value: "1"},];

However, I'm having difficulty passing this return to the montaAutocomplete(source) function because javascript apparently interprets it as a common string and not as an object.

Note that in the image below the variable dados , which is static, is interpreted as an object, whereas the variable source is interpreted as a common string.

How can I convert this result that is returned from autocomplete to an object in javascript?

    
asked by anonymous 03.08.2017 / 15:11

2 answers

1

The best solution would be jQuery.parseJSON

Documentation

var obj = jQuery.parseJSON('[{ label: "Agostinho", value: "1" }]');

example how you could use the mountAutocomplete function:

function montaAutocomplete(source) {

  var dados = [{ label: "Agostinho", value: "1" }];
  //DADOS: VARIÁVEL ESTÁTICA
  document.getElementById('resultado').innerHTML = dados;

  // exemplo
  var obj = jQuery.parseJSON(source);
  //SOURCE: VEM DO BANCO DE DADOS
  //document.getElementById('resultado1').innerHTML = source;
  console.log(obj); // verifica se esta tudo ok


  $("#descricao").autocomplete({
    source: dados,
    minLength: 1, //quantidade de caracteres para começar a buscar
    select: function (event, ui) {
        //evento de quando você seleciona uma opção        
        $("#descricao").val(ui.item.label);
        $("#id").val(ui.item.value);
        event.preventDefault();
      }
  });

}

or even better before calling the function if possible parse the object, so you no longer have to do it inside the function:

var objeto = jQuery.parseJSON(data);
montaAutocomplete(objeto);
    
03.08.2017 / 15:54
-3

I was able to solve with a little research, rs.

If someone is in this situation, use this:

  var dados = eval(source);

The eval () function evaluates or executes an argument.

If the argument is an expression, eval () evaluates the expression. If the argument is one or more JavaScript statements, eval () executes the declarations.

    
03.08.2017 / 15:21