PHP and Jquery's json
My html file:
<script>
$(document).ready(function() {
$.ajax({
type: "POST",
url: "search.php",
data: "id=1",
datatype: "json",
success: function(msg){
$('.result1').html(msg["name"]);
}
});
})
</script>
<span class="result1"></span>
My php file:
<?
$a["name"] = 'john';
echo json_encode($a);
?>
开发者_高级运维Why the name John doesn't appear in class result1? Why? Please help me, I am going insane.
edit: Is it possible to make bounty right now?
The dataType
parameter has a capital T. It works if you correct this.
Currently it is (by default) trying to guess the response format based on the mime-type, so probably defaulting to html - debugging in firebug you can see that the msg
argument of the success callback is a string containing the JSON.
Not to distract you from solving this problem. But you may want to look into the .getJSON() function http://api.jquery.com/jQuery.getJSON/. It's a little cleaner if you're just getting some data.
Also, take a look at the JSON format, I think data: "id=1"
should be data: "{id:1}"
And on the response side, keep in mind it's expecting multiple records so try: msg[0].name;
, check out the each() function to process multiple records.
I think you should use:
$('.result1').html(msg.name);
精彩评论