匿名 js 函数,xhrpost dojo 不返回数据

anonymous js function with xhrpost dojo not returning data

本文关键字:返回 数据 dojo xhrpost js 函数 匿名      更新时间:2023-09-26
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)调用这个函数时,我得到了未定义。即使我采用局部变量并将数据分配给该变量,返回该变量也无济于事。

问题是你的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