使用onclick调用一个函数,该函数从异步函数获取参数

时间:2014-01-03 19:41:31

标签: javascript jquery asynchronous

所以我使用POST从服务器端脚本获取数据,在本例中是变量lotSize。我还有一个名为doS​​omething的函数,它将lotSize作为参数。但是,我想只在单击按钮时执行doSomething。我无法弄清楚如何做到这一点。有人可以帮忙吗?

def doSomething(sqFootage){
    //stuff to do
}

//this post sends address information to a server side script, 
//which returns the variable lotSize
$.post( 
     "/demo.php",
     { 
       pAddress: streetAddress,
       pCity: city,
       pState: state,
       pZip: zipCode     
     },
     function(lotSize) {
        event.preventDefault();

            //I want this function to only execute on a certain onclick
            doSomething(lotSize);

         });

2 个答案:

答案 0 :(得分:0)

这就是你想要做的吗?

$('#IdOfYourButton').click(function(e){
      e.preventDefault();
      $.post( 
     "/demo.php",
     { 
       pAddress: streetAddress,
       pCity: city,
       pState: state,
       pZip: zipCode     
     },
     function(lotSize) {
        event.preventDefault();
        doSomething(lotSize);

     });
});

答案 1 :(得分:0)

参见步骤1至3

// step 1) Put a global variable here, let's call it x
def doSomething(sqFootage){
//stuff to do
}

//this post sends address information to a server side script, 
//which returns the variable lotSize
$.post( 
 "/demo.php",
 { 
   pAddress: streetAddress,
   pCity: city,
   pState: state,
   pZip: zipCode     
 },
 function(lotSize) {
    event.preventDefault();

        //I want this function to only execute on a certain onclick
        //doSomething(lotSize);
        // step 2) Assign lotSize to the global variable x from step 1

     });

// step 3) Create the onclick event handler here and call doSomething(x); where x is the global variable that contains the value from lotSize