在api调用中将硬编码输入转换为变量输入

时间:2019-01-15 17:07:33

标签: javascript here-api

我正在关注矩阵计算器的“这里映射”示例,并使用硬编码值来处理我的工作示例。我想通过遍历变量来将其转换为可用代码,以添加到api调用中。我尝试了很多方法来执行此操作,但是所有方法都会导致400(错误格式的调用)错误

以下代码有效(尽管使用了我的app_code和app_id)

async function getOrderdata(orderId) {
  //await the response of the fetch call
  let response = await fetch('http://localhost:3245/api/Orders/' + orderId);

  //proceed once the first promise is resolved.
  let data = await response.json();

  //proceed only when the second promise is resolved
  return data;
}

我在下面的尝试无效

$.ajax({
    url: "https://matrix.route.api.here.com/routing/7.2/calculatematrix.json",
    type: "GET",
    dataType: "jsonp",
    jsonp: "jsoncallback",
    data: {
        app_code: "xxxxxxxxxxxxxx",
        app_id: "xxxxxxxxxxxx",
        destination0: "52.5488,-3.4974",
        mode: "fastest;car",
        start0: "52.7972,-3.1031",
        start1: "52.5795,-3.8714",
        start2: "52.5735,-3.1266",
        start3: "51.9295,-2.8547",
        start4: "51.9498,-3.5812",
        summaryAttributes: "di,tt"
    },
    success: function(data, status) {
        var i;
        for (i = 0; i < data.response.matrixEntry.length; i++) {
            alert("Start" + i + ": Distance: " + data.response.matrixEntry[i].summary.distance + " Time: " + data.response.matrixEntry[i].summary.travelTime);
        }
    },
    error: function(data) {
        alert("error encountered trying to get mileage");
    }
});

有人可以帮助我提供正确的代码,如果可能的话,我会出问题。

2 个答案:

答案 0 :(得分:0)

我建议您使用开发人员工具(对于浏览器请按F12键)检查您发送的请求。

答案 1 :(得分:0)

使它像这样:

   var myData = {
    app_code: "YOUR_APP_CODE",
    app_id: "YOUR_APP_ID",
    destination0: "52.5488,-3.4974",
    mode: "fastest;car",
    summaryAttributes: "di,tt"
};

// loop thru source locations
for (var i = 0; i < sourceLocations.length; i++)
    myData["start" + i] = parseFloat(sourceLocations[i].lat) + "," + parseFloat(sourceLocations[i].lng);

$.ajax({
    url: "https://matrix.route.api.here.com/routing/7.2/calculatematrix.json",
    type: "GET",
    data: myData,
    success: function (data, status) {
        console.debug(data);
        var i;
        for (i = 0; i < data.response.matrixEntry.length; i++) {
            console.log("Start" + i + ": Distance: " + data.response.matrixEntry[i].summary.distance + " Time: " + data.response.matrixEntry[i].summary.travelTime);
        }
    },
    error: function (data) {
        alert("error encountered trying to get mileage");
    }
});