anonymous js function with xhrpost dojo not returning data

狂风中的少年 提交于 2019-12-25 08:03:56

问题


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;
            }});
    };

When I call this function with cType(withSomeId), I get undefined. Even When I take local variable and assign data to that variable, returning thatvariable also not helping.


回答1:


The problem is that your cType function does not return anything.

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.
 };

You should be using dojo.Deferred to accomplish what you are trying to do:

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 (This has an example that shows the deferred technique)

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



来源:https://stackoverflow.com/questions/10734169/anonymous-js-function-with-xhrpost-dojo-not-returning-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!