【问题标题】:anonymous js function with xhrpost dojo not returning data带有xhrpost dojo的匿名js函数不返回数据
【发布时间】:2012-05-24 08:54:13
【问题描述】:
var cType = function(templateId){
        dojo.xhrPost({
            url : "/mediation1.0.1/template/getCollectorType",
            handleAs : "text",
            headers : {"Content-Type":"text/html"},
            postData : templateId,
            load: function(data){
                    return data;
            }});
    };

当我使用 cType(withSomeId) 调用此函数时,我得到未定义。 即使当我获取局部变量并将数据分配给该变量时,返回该变量也无济于事。

【问题讨论】:

  • 您是否尝试在加载时在控制台上打印响应
  • 是的,在 xhrPost 范围内打印正确
  • dojo.xhrPost 是一个 ajax(异步 Javascript 和 XML)调用。该函数将在解析结果并执行load-handler 之前退出。
  • 这意味着我必须将调用处理程序附加到此请求并从该处理程序访问数据。这就是你的建议?? @安德烈亚斯
  • 顺便说一句,您想从数据 recvd 中做什么?为什么该函数不使用数据并完成所需的工作。

标签: javascript dojo


【解决方案1】:

问题是你的 cType 函数没有返回任何东西。

var cType = function(templateId){
    dojo.xhrPost({
        url : "/mediation1.0.1/template/getCollectorType",
        handleAs : "text",
        headers : {"Content-Type":"text/html"},
        postData : templateId,
        load: function(data){
                return data; 
                // this returns from the the load 
                // function, not the cType function!
        }});

    // You are not returning anything from the cType function.
 };

您应该使用dojo.Deferred 来完成您正在尝试做的事情:

var cType = function(templateId){
  var xhrArgs = {
        url : "/mediation1.0.1/template/getCollectorType",
        handleAs : "text",
        headers : {"Content-Type":"text/html"},
        postData : templateId
  };

  return dojo.xhrGet(xhrArgs);
};

var deferred = cType('templateId');
deferred.then(
  function(data){
      // do something with the data...
  },
  function(error){
      // handle an error calling the server...
  }
);

http://dojotoolkit.org/reference-guide/1.7/dojo/xhrGet.html(这里有一个展示延迟技术的例子)

http://dojotoolkit.org/reference-guide/1.7/dojo/xhrPost.html

【讨论】:

  • 像魅力一样工作。只需在 cType 中添加 return 语句,即 return dojo.xhrGet(xhrArgs);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-12
  • 2013-03-29
  • 1970-01-01
  • 1970-01-01
  • 2014-05-05
  • 2010-12-11
  • 1970-01-01
相关资源
最近更新 更多