When I try to parse JSON from URL through $http.get
I get a strange []
at the end of the string.
The URL I am using is:
http://tol.vpo.si/json/fetchCategories/
and the code:
$http.get('http://tol.vpo.si/json/fetchCategories/',
{
cache: false,
transformResponse: function (data, headersGetter) {
console.log(data);
try {
var jsonObject = JSON.parse(data); // verify that json is valid
return jsonObject;
}
catch (e) {
console.log("did not receive a valid Json: " + e)
}
return {};
}
}
).then(function(resp) {
$scope.categories= resp.data;
}, function(err) {
console.log(err)
});
The answer:
console.log:
[{"ID":"69","IME":"ANALISI TECNICA","D1":"al"},{"ID":"375","IME":"PRIMO PIANO","D1":"prp"}][]
did not receive a valid Json: SyntaxError: Unexpected token [
The URL went succesfully through JSON validation.
Is it possible it is server issue?
Check this working demo: JSFiddle .
By comparing the request headers from the $http
request and a normal request from browsers, I found the difference in header field Accept
. If not specify Accept
, the field is Accept:application/json, text/plain, */*
. Add this code makes the returned data correct:
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
},
Seems the magic option is text/html
. Keep only this value makes it working.
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.