编辑并从获取返回值

时间:2018-12-01 17:28:52

标签: javascript html ajax fetch

我可以通过下面的getvals()函数返回一个自制json页面的数组。不幸的是,我无法找到如何编辑检索到的值以及如何返回它。

这是我第一次使用JavaScript,所以请忍受:)

function getvals(){
return fetch('http://127.0.0.1:5000/mysteps/default',
{
  method: "GET",
  headers: {
    'Accept': 'application/json',
       'Content-Type': 'application/json',
  },
})
.then((response) => response.json())
.then((responseData) => {
  return responseData;
})
.catch(error => console.warn(error));
}

检索到的值如下:

{
"mysteps": [
 {
  "destination": "Death Valley, CA, USA", 
  "duration_text": "2 hours 43 mins", 
  "id": 4, 
  "km": 249.0, 
  "origin": "Bishop, CA, USA", 
  "route_data": "[[-120.483008, 37.303716], [-120.483008, 37.303716]]"
 }, 
 {
  "destination": "merced", 
  "duration_text": "2 hours 9 mins", 
  "id": 5, 
  "km": 210.6, 
  "origin": "San Francisco, CA, USA", 
  "route_data": "[[-118.399663, 37.361368], [-118.399334, 37.36137], 
  [-118.398783, 37.361372], [-118.398282, 37.361379],...

我已经创建了用于编辑数据的代码,即相互添加每条路线以形成行程, 但我无法使用它:

 fetch('/mysteps/' + mysavedtrip).then(function(response) {
     response.json().then(function(data) {
     let optionHTML2 = '';

     for (let mystep of data.mysteps) {
     optionHTML2 += mystep.route_data.replace(/^\[([\s\S]*)]$/, "$1") + ', '
                              }
     optionHTML2 = optionHTML2.slice(0,-2);
     optionHTML2 = "[" + optionHTML2 + "]";
     state_select2.innerHTML = optionHTML2;
     });
   });

我可以显示optionHTML2并看到我想要的输出,但是我要做的是将optionHTML2分配为变量,该变量将在“ getcoordidnates”中提供地图

map.on('load', function () {
   map.addLayer({
     "id": "route",
     "type": "line",
     "source": {
        "type": "geojson",
        "data": {
        "type": "Feature",
        "properties": {},
        "geometry": {
            "type": "LineString",
            "coordinates": getcoordinates                                     
             }
         }
        },
        "layout": {
        "line-join": "round",
        "line-cap": "round"
        },
        "paint": {
        "line-color": "#888",
        "line-width": 3
       }
     });
    });

有什么办法吗?

1 个答案:

答案 0 :(得分:0)

您不会在.then()中返回任何内容,因此提取操作不会返回任何值。

return fetch('/mysteps/' + mysavedtrip).then(function(response) {
  return response.json().then(function(data) {
  let optionHTML2 = '';

  for (let mystep of data.mysteps) {
    optionHTML2 += mystep.route_data.replace(/^\[([\s\S]*)]$/, "$1") + ', '
                          }
    optionHTML2 = optionHTML2.slice(0,-2);
    optionHTML2 = "[" + optionHTML2 + "]";
    state_select2.innerHTML = optionHTML2;
    return optionHTML2;
 });
});

将上面的代码添加到函数getvals()后,该函数应返回一个值为optionHTML2的promise。

因此您可以像这样使用它:

getvals().then(function(optionHTML2) {
  do what you want with the optionHTML2 here.
})