I want to retrieve the houseType
and this is the api call using ajax. Only Console.log
for result
is fine but the others show undefined
. I don't know why it happens.
$.ajax({
url: 'http://api/get.php',
type: 'GET',
crossDomain: true,
datatype:'json',
data:{
HouseNo: 2001
},
success: function(result) {
console.log(result);
console.log(result.error);
console.log(result.houses);
console.log(result.houses.houseType);
if (result.error == false) {
window.location.href = "viewHouses.php"
}
},
error: function(result) {
alert("Error");
}
});
The console log result
is
{"error":false,"houses":[{"houseType":"Mansion"}]}
but the logs of result.error
and result.houses
are undefined
. What am I missing?
As the jquery docs state:
"json": Evaluates the response as JSON and returns a JavaScript object. Cross-domain "json" requests are converted to "jsonp" unless the request includes jsonp: false in its request options. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown.
If you are requesting the data with a cross-origin request, the options should have a jsonp: false
value:
$.ajax({
url: 'http://api/get.php',
type: 'GET',
crossDomain: true,
datatype:'json',
jsonp: false,
data:{
HouseNo: 2001
},
success: function(result) {
// ...
},
error: function(result) {
// ...
}
});
To me this looks like you're actually logging a JSON(P) string of some sort. If the above does not work try parsing result
with:
try {
var parsed = JSON.parse(result);
console.log(parsed);
} catch(err) { console.log(err); }
I'm curious what this snippet would log.
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.