【问题标题】:consume webservice using dojo使用 dojo 使用 web 服务
【发布时间】:2012-02-27 17:06:48
【问题描述】:

我想使用 dojo 来使用 Restful 网络服务。 在浏览器上返回 web 服务的结果,但是当我尝试使用 xhr 获取结果时,我总是得到一个空值,所以请帮助我是 dojo 的新手...

dojo.query("li").onclick(function(){
        var xhrArgs = {
                url: "http://192.168.1.65:9080/RAD8JAX-RSWeb/jaxrs/customers",

                handleAs: "json",
                headers: { "Content-Type": "application/json"},
                load: function(data) {
                alert("ok");
                    console.log(data);
                },
                error: function(error) {
                    console.log(error);
                }
            };
             dojo.xhrGet(xhrArgs);
 console.log("message sent ...");
});

当事件发生时,会显示警报,我得到“null”

【问题讨论】:

标签: javascript json rest dojo


【解决方案1】:

实际上,dojo.data API 比新的 dojo.store APIs(从 1.6 开始提供)更严格。

为了使用宁静的网络服务,我的建议是使用dojo.store.JsonRest 存储。不需要特定的 Json 格式。

这是一个很好的 JsonRest 用法示例:http://dojotoolkit.org/documentation/tutorials/1.7/store_driven_tree/

【讨论】:

  • 呵呵,每天都学点新东西……不知道 JsonRest 商店。
【解决方案2】:

Dojo 使用“存储”从服务器获取数据。这些存储会懒惰地出去并获取数据,因此只有在您第一次请求时。每次您的 JavaScript 代码需要数据时,它都可以向 store 询问,如果它已经获取了它,它将返回它,否则它将出去并获取它。

由于存储的异步特性,您每次需要数据时都需要进行异步调用。

在您的情况下,您可以执行以下操作:

// Create the store for later use
var store = new dojo.data.ItemFileReadStore({
  contentType: 'application/json'
  ,clearOnClose: true
  ,urlPreventCache: true
  ,url: "http://192.168.1.65:9080/RAD8JAX-RSWeb/jaxrs/customers"
});

而且每次你​​需要从你的商店获取数据时:

store.fetch({
  onItem: function(item, request) {
    alert('I fire after each returned json item')
  }
  ,onComplete: function(items, findResult) {
    alert('I fire when the data has loaded completely.');
  }
  ,onError: function(error, request) {
    alert('I fire when an error occurs');
  }
});

只有第一次才会有请求发送到服务器。所有其他请求将从商店缓存中提供。如果要刷新缓存,则需要“关闭”存储。下次在 store 上调用 fetch 将导致对服务器的新请求。您可以像这样关闭它:

store.close();

商店旨在以透明的数据技术方式提供服务器数据。因此,无论您提供 json、xml 还是 csv,都无关紧要:它们都将加载到存储中并以相同的方式提供给您。你只需要知道两件事:

  1. 数据需要以特定格式提供:格式见http://livedocs.dojotoolkit.org/dojo/data/ItemFileReadStore#item-structure-examples
  2. 您在 onItem 和 onComplete 方法中获得的所有项目只能通过 dojo Read API 使用,您可以在此处阅读:http://dojotoolkit.org/api/1.7/dojo/data/api/Read

存储的类型很多,ItemFileReadStore 只是一个例子。

希望对你有帮助

【讨论】:

  • 非常感谢我真的很喜欢你的帮助我试试这个我想向你展示当我调用 web 服务时将生成的 json [{"lastName":"Ziosi","title": "Mr","firstName":"Lara","ssn":"888-88-8888 "}] 我该如何处理,这是一个 jsonArray :/
  • 数组未命名这样使用有问题吗?
  • 如果您阅读livedocs.dojotoolkit.org/dojo/data/…,您会发现商店需要另一个 json 结构。您需要将数组包装在这样的结构中: { "identifier": "id", "items:[{id: 1. ...other info of this item...},{Id: 2, .. .该项目的其他信息...}等] }
  • 虽然与问题相关,但这并不是对提问者提出的具体问题的回答。
  • 怎么样,假设我们没有 REST 完整服务? JSON 是动态的,我们无法从服务器进行更改,但仍想过滤数据。我们怎样才能实现它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-11
  • 1970-01-01
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多