简单的jQuery php json无法正常工作
问题描述:
I got this in my html :
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script>
$.post("mm.php", { func: "getNameAndTime" },
function(data){
$(data).each(function() {
$("div").append($(this).name);
});
}, "json");
</script>
<div></div>
And my mm.php
looks like this :
<?php echo json_encode(array("my" => array("name"=>"John","time"=>"2pm"), "ur"=>array("name"=>"Nah","time"=>"1:13")) ); ?>
This was working before i putted the .each()
so doesnt have the including or other problems.
Why isnt this working ? Where have i been going wrong ?
答
data
is not a DOM element, it's a JSON object. You need to use $.each
instead of .each()
Also, inside the each()
, this
is an object, not a DOM element, so you don't need $()
around it.
$.each(data, function() {
$("div").append(this.name);
});
EDIT: Instead of using this
inside the each
try this:
$.each(data, function(i,v) {
$("div").append(v.name);
});
答
This:
$("div").append($(this).name);
Should be:
$("div").append(this.name);