I am trying to load names from a html-file consisting of json-data. The problem is that the page is blank/white and no error message in the firefox debugger.
the test.html and persondb.html is on the same server.
test.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>JSON Exempel</title>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<ul id="person-lista">
</ul>
<script>
$.ajax({
url: "http://www.mywebbpage.com/ajax/persondb.html", // not the realname
data: {
limit: 5,
name: 'ra'
},
success: function (response) {
var personArray = response.personer;
for(var i=0; i < personArray.length; i++) {
var person = personArray[i];
$('#person-lista').append('<li>' + person.fnamn + '</li>');
}
}
});
</script>
</body>
</html>
persondb.html
{
"personer": [{
"fnamn": "RACHELLE",
"enamn": "ZWIEFELHOFER",
"epost": "rachelle.zwiefelhofer@somefakedomain.nu"
}, {
"fnamn": "RACQUEL",
"enamn": "JOH",
"epost": "racquel.joh@somefakedomain.nu"
}, {
"fnamn": "RAE",
"enamn": "BRAVARD",
"epost": "rae.bravard@somefakedomain.nu"
}, {
"fnamn": "RAFAEL",
"enamn": "SAGASTUME",
"epost": "rafael.sagastume@somefakedomain.nu"
}, {
"fnamn": "RAISA",
"enamn": "REINES",
"epost": "raisa.reines@somefakedomain.nu"
}]
}
is the persondb.html not formatted correctly? is that the reason? When loading the persondb.html in a browser it look likes the following
{ "personer": [{ "fnamn": "RACHELLE", "enamn": "ZWIEFELHOFER", "epost": "rachelle.zwiefelhofer@somefakedomain.nu" }, { "fnamn": "RACQUEL", "enamn": "JOH", "epost": "racquel.joh@somefakedomain.nu" }, { "fnamn": "RAE", "enamn": "BRAVARD", "epost": "rae.bravard@somefakedomain.nu" }, { "fnamn": "RAFAEL", "enamn": "SAGASTUME", "epost": "rafael.sagastume@somefakedomain.nu" }, { "fnamn": "RAISA", "enamn": "REINES", "epost": "raisa.reines@somefakedomain.nu" }] }
Or is it problem with the "same origin policy" ? But the files is on the same server (same folder)
You need to parse your JSON before you can access it in your loop -
success: function (response) {
var res = JSON.parse(response);
var personArray = res.personer;
for(var i=0; i < personArray.length; i++) {
var person = personArray[i];
$('#person-lista').append('<li>' + person.fnamn + '</li>');
}
}
You have to parse JSON, as EatPeanutButter mentioned, or you have to send a correct Content-Type (application/json) with the response of your html-page. Your JSON is well formed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.