M
M
Monitorkin2016-03-04 10:54:48
JavaScript
Monitorkin, 2016-03-04 10:54:48

How to get JSON data in Yii2 from view?

I can't get the script to work in Yii2 to get json data from the database.
there is a file /modules/maps/views/object/objectsjson.php (simplified .., in general, the data is taken from the database):

echo '{
    "type": "FeatureCollection",
    "features": [
        {"type": "Feature", "id": 0, "geometry": {"type": "Point", "coordinates": [55.831903, 37.411961]}, "properties": {"balloonContent": "Содержимое балуна", "clusterCaption": "Еще одна метка", "hintContent": "Текст подсказки"}},
        {"type": "Feature", "id": 1, "geometry": {"type": "Point", "coordinates": [55.763338, 37.565466]}, "properties": {"balloonContent": "Содержимое балуна", "clusterCaption": "Еще одна метка", "hintContent": "Текст подсказки"}}
        ]
}';

and there is a javascript that accesses this file (example taken from here ):
ymaps.ready(init);
function init () {
    var myMap = new ymaps.Map('map', {
            center: [сenter1,сenter2],
            zoom: 1,
      type: 'yandex#satellite'
        }),
        objectManager = new ymaps.ObjectManager({
            clusterize: true,
            gridSize: 32
        });
myMap.geoObjects.add(objectManager);
    $.ajax({
        url: "http://site.ru/basic/web/index.php?r=maps%2Fobject%2Fobjectsjson"
    }).done(function(data) {
        objectManager.add(data);
    });

}


the output is empty .. but if you put this file in the web folder and write
$.ajax({
        url: "objectsjson.php"
    }).done(function(data) {
        objectManager.add(data);
    });

then everything works!
Where is the mistake? Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill Arutyunov, 2016-03-04
@arutyunov

dataType: 'json' specify in js (in ajax)
Specify json format in action:
And why does your view give json if the data from the database can be placed in an array, and the array can be given as json? You just specify the data format as JSON in the action and do return $array;

public function actionMessage()
    {
        // Получение данных из модели, действия с данными
        // ...

        Yii::$app->response->format = Response::FORMAT_JSON;
        return [
            'status' => 'success',
            'message' => $model
        ];
    }

As a result, the code will return JSON.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question