JavaScript 中的 Web 服务调用和 JSON 数组操作

web service call and JSON array manipulation in javascript

本文关键字:JSON 数组 操作 调用 中的 Web 服务 JavaScript      更新时间:2023-09-26

我需要从javascript调用一个Web服务,该服务以以下格式返回一个JSON数组:

["hello","there","I","am","an","array"]

不幸的是,我正在使用的javascript库(Sencha Touch)将这些数据加载到小部件中,不接受该格式作为数据输入。 但是,它将适用于这样的东西:

[["hello"],["there"],["I"],["am"],["an"],["array"]]

所以这里有两个问题 - 如何在javascript中调用该Web服务,然后将返回的数组操作为我需要的格式? 我一直在研究jQuery的getJson()方法,不确定这是否是要走的路,或者是否有更好的方法。

提供 JSON 数组的 URL 就在这里。 感谢您的帮助。

这是一个jsFiddle,显示了你问的两个部分。我正在使用jQuery进行我的AJAX调用(在jsFiddle中伪造),并且我使用Underscore.js进行操作:

http://jsfiddle.net/JohnMunsch/E7YTQ/

// Part 1: Get the raw data. Unfortunately, within a jsFiddle I can't go get it from a different domain. So I'm
// simulating the call instead.
var rawDataPromise = $.ajax({
    url : "/echo/json/",
    data : fakeData,
    type : "POST"
});
// var rawDataPromise = $.ajax("http://fastmotorcycleservice.cloudapp.net/FastMotorCycleListService.svc/list/Bruno");
rawDataPromise.done(
  function (results) {
    // Part 2: Manipulate the data into the form we need.
    var manipulatedResults = _.map(results, function (item) { return [ item ]; });
    console.log(manipulatedResults);
  }
);
// You could also pull that together into a single call $.ajax(...).done(function (results) { ... });

一旦你有一个局部变量中的数据,你就可以根据需要操作它:

var data = the_function_you_use_to_get_data();
var formatted_array = new Array();
for(i in data){
    var d = new Array();
    d[0] = i;
    formatted_array.push(d);
}

我希望它回答了你的问题