简体   繁体   中英

passing parameters to a javascript function alongwith a callback

I have a link in my html page like the on below :

<a id="save_report" href="javascript:void(0);" title="Save Report" onclick="javascript:enterReportNameToSave(<?php echo $upload_count?>,<?php echo $startOffset;?>,<?php echo $affiliateId; ?>);">Save Report <img height="16" width="16" style="vertical-align: bottom;" src="/img/icn_export.gif" alt="export"></a>

As, you can see , I need to send few parameters to the function enterReportNameToSave and at the same time , I need to invoke a callback function as well to handle a popup .

My enterReportNameToSave() function invocation will be something like :

function enterReportNameToSave(count,startOffset,user_id,f)
{
     //Some logic to set a div element based on the parameter values
     f()//This will be the implementation of my call function
     {
         //Here I need to invoke the popup logic
      }
}

Here I'm confused with the correct implementation of this , I mean what's the correct way to implement the scenario. Please help.

Hope you find this useful.

function enterReportNameToSave(count,startOffset,user_id,f)
{
$("#yourdivid").html("<h1>Show Loading bar or load up your actual html data here</h1>").load("use_this_if_data_needs_fetching_from_remote.php","count="+count+"&f="+f,function() {
   alert("I am just a useless popup and have popped up after the div is populated");
});
}

Suppose you have various callback functions in Javascript:

function f1(count, offset, uid) {
    alert("count=" + count);
}    
function f2(count, offset, uid) {
    alert("offset" + offset);
}
// etc

In PHP you can pass the name of the callback function to your constructed onclick function as a further parameter:

onclick="javascript:enterReportNameToSave(<?php echo $upload_count; ?>, 
    <?php echo $startOffset; ?>, <?php echo $affiliateId; ?>, 
    <?php echo $callback_name; ?> );">

The concrete value of the onclick string would be eg

onclick="javascript:enterReportNameToSave(10, 20, 1234, f1);"

The Javascript function enterReportNameToSave() looks like:

function enterReportNameToSave(count, startOffset, user_id, f) {
    // use parameters count, startOffset, user_id
    // call callback function f:
    f(count, startOffset, user_id);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM