Here is another JSON question (I always struggle with arrays).
My PHP code returns the following JSON structure:
[{"breed":{"msg":"Breed is required","placement":"#breed_error_1","return":"false"}},{"breed":{"msg":"Breed does not exist","placement":"#breed_error_2","return":"true"}}]
My PHP code is:
$breed[]["breed"] = array("msg"=>"Breed is required","placement"=>"#breed_error_1", "return"=>"false");
$breed[]["breed"] = array("msg"=>"Breed does not exist","placement"=>"#breed_error_2", "return"=>"true");
And 开发者_如何转开发the AJAX code:
$.ajax({
type: 'POST',
cache: false,
url: "validate_breed",
data: element+"="+$(elementSelector).val()+"&v="+validateElement,
context: document.body,
dataType: 'html',
success: function(data){
alert(data);
}
});
alert(data)
alerts out the JSON structure for debugging purposes.
How do I access the breed section of JSON object and all of the following index/keys?
A for(item in data)
loop should do the trick, there are other articles around that talk about getting the values
actually How do I loop through or enumerate a JavaScript object?
Here is the JSON reformatted:
[
{
"breed":{
"msg":"Breed is required",
"placement":"#breed_error_1",
"return":"false"
}
},
{
"breed":{
"msg":"Breed does not exist",
"placement":"#breed_error_2",
"return":"true"
}
}
]
What you have is an array []
of two objects {}
.
To start with you'd do a for (var i = 0; i < JSON.length; i++)
loop to get each object (of which you have 2).
Snippet:
for (var i = 0, len = JSON.length; i < len; i++){
thisBreed = JSON[i].breed; //now this == {"msg" : etc etc}
for (prop in thisBreed) {
console.log(thisBreed.msg + thisBreed.placement + thisBreed.return);
}
}
Use console.info
in FireFox and you'll be able to visualize the object.
The simplest way ensure proper json is to bulid the array in php tw way you want it then use http://php.net/manual/en/function.json-encode.php on the array befor you send it back
Here is the JSFiddle Demo:
For instance if this is your output JSON object, then you can access index of each breed using a for loop:
var myJSON = [{
"breed": {
"msg": "Breed is required",
"placement": "#breed_error_1",
"return": "false"
}},
{
"breed": {
"msg": "Breed does not exist",
"placement": "#breed_error_2",
"return": "true"
}}];
for(var i=0;i<myJSON.length; i++){
console.log(myJSON[i].breed);
}
This would console output two objects under each of the two breed
Try This one
for (var i = 0, len = JSON.length; i < len; i++){
console.log(JSON[i].breed.msg +" - "+ JSON[i].breed.placement +" - "+ JSON[i].breed.return);
}
精彩评论