TypeError: data.forEach is not a function

前端 未结 5 1540
孤街浪徒
孤街浪徒 2021-01-18 06:38

This is my code:

$.ajax({
    url: \"some_url/\",
    type: \"GET\",
    dataType: \"json\",
    success: function(data){
        console.log(data);
                 


        
5条回答
  •  北荒
    北荒 (楼主)
    2021-01-18 07:19

    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);
        });
    }
    

提交回复
热议问题