F
F
Fevralskiy2019-06-28 11:02:45
HTML
Fevralskiy, 2019-06-28 11:02:45

How to output JSON response to html?

Hello!

There is an html page with a form that sends data to a third-party resource using an Ajax request (GET) and receives a JSON response. The question is how to snatch 2 parameters from the answer and display them in a div under the above form?

Here is my request:

$(document).ready(function(){
$('#cdek').on('submit',e => {
e.preventDefault(); // не даст сработать стандартному действию браузера при отправке формы, вместо этого еще можно "return false;" но в конце этого блока с кодом
    $.ajax({
        type: 'GET',
        url: 'https://kit.cdek-calc.ru/api/', // куда уходят данные с формы
        data: $('#cdek').serialize(), // сериализуем данные с формы
        success: function(data){

          }
      });
  });
});


And the answer looks like this:

{
  
  "136":
  {
    "info":
    {
      "id":"136",
      "name":"Посылка склад-склад",
      "description":"До 30 кг. Услуга экономичной доставки товаров по России для компаний, осуществляющих дистанционную торговлю.",
      "im":1
    },
    "result":
    {
      "price":"165.00",
      "insurance_price":"7.50",
      "pod":"0.00",
      "total_price":"172.50",
      "day_min":2,
      "day_max":3,
      "date_min":"2017-08-09",
      "date_max":"2017-08-10"
    }
  }
}

Attached a picture:
5d15c8337fcfa529845807.jpeg

How to display ("name":"Parcel warehouse-warehouse",) and ("total_price":"172.50",) in div id="answer"?

Is it possible to make the conclusion universal? the answer can be with another tariff? For example:

{
  "1":
  {
    "info":
    {
      "id":"1",
      "name":"Экспресс лайт дверь-дверь",
      "description":"До 30 кг. Классическая экспресс-доставка по России документов и грузов.",
      "im":0
    },
    "result":
    {
      "price":"670.00",
      "insurance_price":"0.00",
      "pod":"0.00",
      "total_price":"670.00",
      "day_min":2,
      "day_max":2,
      "date_min":"2017-08-09",
      "date_max":"2017-08-09"
    }
  }
  
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Derepko, 2019-06-28
@Fevralskiy

This is inserted into the ajax callback

success: (response)=>{
    const keys = Object.keys(response);
    const data = response[keys[0]];
    const info = data.info;
    const name = info.name;
    $("#divId").html('<p>name: ' + name + '</p>');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question