Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/439.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
试图从javascript模块获取返回值_Javascript_Object_Module_Return - Fatal编程技术网

试图从javascript模块获取返回值

试图从javascript模块获取返回值,javascript,object,module,return,Javascript,Object,Module,Return,我有以下代码: $("#search").keyup(function(){ if($("#search").val().length > 2){ var returnedValue = (notes.search($("#search").val())); console.log(returnedValue); } }); notes = (function(){ return{

我有以下代码:

    $("#search").keyup(function(){
      if($("#search").val().length > 2){
        var returnedValue = (notes.search($("#search").val()));
        console.log(returnedValue);
      }
    });


    notes = (function(){

    return{

        search : function(data){
                var result = "";
                $.ajax({
                    type:"GET",
                    url:"/search",
                    dataType:"text",
                    timeout:2000,
                    data:{noteTitle:data},
                    success:function(data){
                        if(data == 'false'){
                            console.log('no data');
                        }else{
                            result = JSON.parse(data);
                            return(result);
                        }
                    },
                    error:function(xhr,type){
                        console.log("ajax error");
                    }
                });
        },
})();

返回值总是未定义的。这显然是一个范围问题,但我似乎不知道如何将ajax请求中的数据返回到模块之外的任何对象。

数据变量被覆盖

更正代码:

$("#search").keyup(function(){
  if($("#search").val().length > 2){
    var returnedValue = (notes.search($("#search").val()));
    console.log(returnedValue);
  }
});


notes = (function(){

return{

    search : function(str){
            var result = "";
            $.ajax({
                type:"GET",
                url:"/search",
                dataType:"text",
                timeout:2000,
                data:{noteTitle:str},
                success:function(msg){
                    if(msg== 'false'){
                        console.log('no data');
                    }else{
                        result = JSON.parse(msg);
                        return(result);
                    }
                },
                error:function(xhr,type){
                    console.log("ajax error");
                }
            });
    },

})();

这个IEFE是完全不必要的。IIFE用于将变量包含在有限的范围内,因为javascript中的变量定义的范围是定义它们的函数,而不是块。在本例中,您使用函数的返回值初始化全局(notes)。没有必要把它包装在生活中。把jQueryPromise模式作为替代方案,但您会如何使用模块模式进行结构呢?嘿,迭戈。这一联系就是答案。谢谢你的提醒。仅供参考,这没用。我仍然没有定义。