34
I believe data is a JSON string. Since forEach()
is a array function and you are trying to implement it on the JSON string it throws the error:
βUncaught TypeError: data.forEach is not a functionβ
You have to parse the data with JSON.parse()
before using forEach()
:
The
JSON.parse()
method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
data = JSON.parse(data);
Demo:
var data = JSON.stringify([{"model": "app.mdl", "pk": 1, "fields": {"name": "test", "rank": 1}}]);
data = JSON.parse(data);
data.forEach(function(element){
console.log(element);
});
So the success should be:
success: function(data){
data = JSON.parse(data);
console.log(data);
data.forEach(function(element){
console.log(element);
});
}
2
just check for either it is string or JSOn array
if(typeof(data) === "string"){data = JSON.parse(data)}
data.forEach(function(element){
console.log(element);
});
- [Django]-Switching to PostgreSQL fails loading datadump
- [Django]-PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django
- [Django]-Determine variable type within django template
0
Just check if the data is JSON string.
data = "[{"model":"app.mdl","pk":1,"fields":{"name":"test","rank":1}}]"
if yes, the you have to do JSON.parse(data) and do forEach on it.
- [Django]-Django 2 β How to register a user using email confirmation and CBVs?
- [Django]-Detect mobile, tablet or Desktop on Django
- [Django]-Django + Ajax
0
It is a case where your data
response looks like an array but it is a string. If you have access to the API youβre connecting to you can ensure the response it sends out is an array but if not simply parsing the data
response using JSON.parse()
should do the trick.
- [Django]-How can I get MINIO access and secret key?
- [Django]-Disabled field is not passed through β workaround needed
- [Django]-How can I avoid "Using selector: EpollSelector" log message in Django?
0
Change your success function to this, the JSON.parse()
function is required to iterate over the JSON string:
success: function(data){
data = JSON.parse(data);
console.log(data);
data.forEach(function(element){
console.log(element);
});
- [Django]-Itertools.groupby in a django template
- [Django]-How to test "render to template" functions in django? (TDD)
- [Django]-Django Rest Framework model serializer with out unique together validation
0
$.ajax({
url: "some_url/",
type: "GET",
dataType: "json",
success: function(data){
console.log(data);
data.data.forEach(function(element){
console.log(element);
});
}
});
// Just add - data.data.foreach.
- [Django]-How do I match the question mark character in a Django URL?
- [Django]-How to delete project in django
- [Django]-What does 'many = True' do in Django Rest FrameWork?