开发者

Spot the error - Mixing: php data objects (fetch object), json, and jquery.post()

Can anyone better experienced then me, spot the issue here. I'm unable to debug it, my var_dumps don't seem to get any effect due to the use of jquery.post() so I believe.

I get nothing displayed. I was expecting to receive a li series filled with json encoded values.

The HTML:

<div id='data'></div>
<form action="">
  <input id="nomeInput" type="text" name="nomeInput" value="" autocomplete="false"/>
</form>
<ul id="listaDominios" style="display: none;">
</ul>

The js:

$(document).ready(function(){
  $('#nomeInput').keypress(function(){
     $.post("testeBasico_1.php", {nomeInput : $('#nomeInput').val()}, function(resposta) {
        for (var x = 0, tamanhoDados = resposta.nomeDominio.length; 开发者_StackOverflowx < tamanhoDados; x++){
           $('#listaDominios').show();
           $('#listaDominios').append('<li>'+resposta.nomeDominio[x]+'</li>');
        }

      }, "json");

  });//end of keypress;

});//end of document ready;

The PHP

public function listaDominios(DominioVo $dominioVo)
{
  try
  {
     $stmt = $this->_dbh->prepare("SELECT d.nomeDominio FROM dominio d WHERE d.nomeDominio LIKE ?");
     $stmt->bindValue(1,'%' . 'a' . '%', PDO::PARAM_STR);
     $stmt->execute();

     $resultado = $stmt->fetchAll(PDO::FETCH_OBJ);

       return $resultado;
    }
    catch (PDOException $ex)
    {
      echo "Erro: " . $ex->getMessage();
    }
}

If the spot gets to be a difficult catch, how can I spot it. It's my first ajax experience, so I'm not comfortable with the debugging part. :s

Suspicion: (UPDATE) I believe the issue is in the way I'm trying to iterate over the returned json. Here's the echo format of the json_encoded:

[{"nomeDominio":"aaaa.ka"},{"nomeDominio":"agentesdeexecucao.ka"}]

Thanks a lot in advance, MEM


Since the base of the object is an array you need to iterate over it at the root level, so your for loop should look like this:

$('#listaDominios').toggle(resposta.length > 0);
for (var x = 0; x < resposta.length; x++){
  $('#listaDominios').append('<li>'+resposta[x].nomeDominio+'</li>');
}

Or the $.each() route:

$('#listaDominios').toggle(resposta.length > 0);
$.each(resposta, function() {
  $('<li />', { text: this.nomeDominio }).appendTo('#listaDominios');
});

The important part is that resposta.nomeDominio isn't anything, since the root of the response is an Array, however resposta.length will get the length, so use that. Also since the array is at the root and each object in it has a nomeDominio property, you want resposta[x].nomeDominio to go to the current index (to get the object), then call .nomeDominio to get the property. Or, use the $.each() route in which this refers to the current object, either way works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜