如何传递chid函数返回作为父函数的返回

时间:2016-04-08 04:09:57

标签: javascript

        function myValidationAction2(fieldValue){       
        var c=fieldValue;
         var d1;

        function foo(callback)
        {   
            var abc=null;

            if(window.XMLHttpRequest) // DETECT ALL BROWSER RATHER THEN IE 
            {
                abc=new XMLHttpRequest();
            }
            else if(window.ActiveXObject) // DETECT IE
            {
                abc=new ActiveXObject("Microsoft.XMLHTTP");
            }
            // SEND REQUEST TO SERVER
            abc.open("GET","ajax4.php?txt_email="+c);


            abc.send();
            abc.onreadystatechange=function()
            {
                if(abc.readyState==4)
                {


                    callback($(abc.responseText).text());


                }


            }

        };

        foo(function(result)
        {
            //here result is display Successfully.
            //i want to pass result as return of function parent function myValidationAction2.....
        });


    }

简而言之,我希望在第一次执行函数时返回abc.responsetext中的返回true或false。所以我使用callbcak来调用foo函数(函数(result));结果是在功能上成功但我不想修改结果而是我想将结果作为父函数的返回返回。



<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<form method="post">
  <input type="submit" name="submit" id="submit">
</form>

<script type = "text/javascript">
$(document).ready(function(){
   
  
  $("#submit").click(function(){
    var a=myValidationAction21("hello");//but what if it is callback function how to get return value in variable a
          
    alert("a="+a);
  });
  
  function myValidationAction21(fieldValue,callback) { // callback arg. here!!
	alert("i am execit");
	alert("fieldValue"+fieldValue);
	
    
  };

/*my approach for callback is

    function myValidationAction21(fieldValue,callback) { // callback arg. here!!
	alert("i am execit");
	callback(fieldvalue);
	
    
  };
  
  var a=myValidationAction21("", function( responseFromFoo ) {
     				return responseFromFoo;
    			});
				alert("a==="+a);//give UNDEFINED 
*/  
 

	

});
</script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

简而言之:

function myValidationAction2(fieldValue, callback) { // callback arg. here!!

  function foo() {   // (not here)
    var abc=null;
    if(window.XMLHttpRequest) {      // DETECT ALL 
      abc=new XMLHttpRequest();
    }else if(window.ActiveXObject) { // DETECT IE
      abc=new ActiveXObject("Microsoft.XMLHTTP");
    }
    // SEND REQUEST TO SERVER
    abc.open("GET","ajax4.php?txt_email="+ fieldValue);
    abc.send();
    abc.onreadystatechange=function(){
      if(abc.readyState==4) {
        callback( $(abc.responseText).text() );
      }
    };
  }

  foo();

}

并使用如:

myValidationAction2("someFieldVal", function( responseFromFoo ) {
     console.dir( responseFromFoo );
});