开发者

Using JSON object question

开发者 https://www.devze.com 2023-02-04 01:27 出处:网络
OK so i have this script that submits the input of a search box to a .php and gives back a JSON object in jquery. How can i now change the content of a div. The JSON object that is returnd looks like

OK so i have this script that submits the input of a search box to a .php and gives back a JSON object in jquery. How can i now change the content of a div. The JSON object that is returnd looks like this:

{"0":"Aardappelen rauw","voedsel":"Aardappelen rauw","1":"88","calorien":"88"}

How can i say that 'Aardappelen rauw' should be in div1 and 88 in div 2 for example? I tried with data.voedsel and data.calorien but that doesn't work..

in head:

<script type="text/javasc开发者_开发问答ript">
function contentDisp()
{

$.ajax({
  type: 'POST',
  url: 'getFood.php',
  data: {'foodnametextbox' : $('#food').val() },
  datatype: "json",
  success: function(data){ 

    $('.second').replaceWith(data);

  }
});


}
</script>

in body:

<div class="container">
  <div class="inner first">Hello</div>
  <div class="inner second">And</div>
  <div class="inner third">Goodbye</div>
</div>


The dataType: 'json' should automatically call parseJSON. Then you should be able to do data['0'] (or data.voedsel) to get 'Aardappelen rauw'.

EDIT: Change datatype: "json" to dataType: "json". The 't' in 'type' needs to be capital.


You can use .parseJSON() http://api.jquery.com/jQuery.parseJSON/


replaceWith takes a HTML string, DOM element, or jQuery object. A JSON data object is neither of those. My guess is you want something like this:

$('.second').text(data["0"]);

EDIT: Don't use eval. Your ajax option is wrong. It needs to be dataType: 'json'. Note the capital T.

0

精彩评论

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