【问题标题】:What is the right way to send JSON to clients?将 JSON 发送给客户端的正确方法是什么?
【发布时间】:2015-09-22 07:46:10
【问题描述】:

我想为 Pebble 开发一个应用程序。这个应用程序会告诉你从你在选项中设置的一个地方到另一个地方需要多长时间,考虑到交通拥堵和其他事情。 为此,我需要创建一个返回 JSON 的页面。 Pebble 使用如下代码检索信息:

var cityName = 'London';
var URL = 'http://api.openweathermap.org/data/2.5/weather?q=' + cityName;

ajax(
 {
  url: URL,
  type: 'json'
},
function(data) {
  // Success!
  console.log('Successfully fetched weather data!');
},
function(error) {
  // Failure!
  console.log('Failed fetching weather data: ' + error);
}
);

我创建了一个带有 js 脚本的小页面,该脚本从 Yandex API 获取所需信息:

    var route;
      ymaps.ready(init);
var myMap;

function init(){    


  function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  }   

        var time = 0;
        var home = getParameterByName("h");
        var work = getParameterByName("w");
      ymaps.route([home, work],{avoidTrafficJams: true}).then(
            function (router) {
                route=router;
                time = ((route.getTime())/60).toFixed(2);

               var info = new Object;
                info["home"] = home;
                info["work"] = work;
                info["time"] = ~~time+"m"+~~((time%1)*60)+"s";
                JSON.stringify(info);
            },
            function (error) {
                alert('Возникла ошибка: ' + error.message);
            }
            );    
}

如您所见,最后我可以得到一个 JSON 字符串。但是,当发出带有正确参数的请求时,如何将其发送给客户端?

【问题讨论】:

    标签: javascript json pebble-watch


    【解决方案1】:

    我最终使用了 phantomjs 并在我的 php 页面上执行了这个 js 脚本。

    【讨论】:

      猜你喜欢
      • 2021-05-25
      • 2020-03-06
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 1970-01-01
      • 2018-09-22
      相关资源
      最近更新 更多