2016-04-08 105 views
0
 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..... 
     }); 


    } 
總之

我想給返回true或false這是進來abc.responsetext作爲第一次函數executed.So我使用callbcak到foo函數稱爲foo(function(result));結果是成功comed函數,但我不想修改結果,而是我想返回結果作爲父函數的返回。如何通過CHID函數返回父函數返回

<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!! 
 
\t alert("i am execit"); 
 
\t alert("fieldValue"+fieldValue); 
 
\t 
 
    
 
    }; 
 

 
/*my approach for callback is 
 

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

 
\t 
 

 
}); 
 
</script>

回答

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

怎麼稱呼?函數請詳細描述 – amir

+0

我打電話就像這個功能 – amir