往返回调

I have an Ajax call with a callback. (I am using YUI for this). The basic call looks like this:

function something() {
  var callback1_success = function (o) {…
  };
  var callback1_failure = function (o) {…
  };
  var callback1 = {
    success: callback1_success,
    failure: callback1_failure
  };
  var callback2_success = function (o) {…
  };
  var callback2_failure = function (o) {…
  };
  var callback2 = {
    success: callback2_success,
    failure: callback2_failure
  };
  var ajax_params = buildAjaxParams(….);
  Y_GET(ajax_params, callback1);
  var ajax_params = buildAjaxParams(….); // different stuff
  Y_GET(ajax_params, callback2);
} // something

function Y_GET(p_parms, p_callback) {
  request = YAHOO.util.Connect.asyncRequest('GET', p_parms, p_callback);
  return (request);
} // Y_GET
This all works fine.What I want to do is send the callback to the server, the server will not process the callback parameters and will send them back in the result set.

So, Y_GET will become: Function Y_GET(p_parms, p_callback) {
  var parms_to_send = p_parms + “ & passthrough = ” + p_callback;
  request = YAHOO.util.Connect.asyncRequest('GET', parms_to_send, local_callback);
  return (request);
} // Y_GET
var local_callback = {
  success: function (o) {
    o.responseText.passthrough.success
  },
  failure: function (o) {
    o.responseText.passthrough.failure
  }
}; /*   paste in your code and press Beautify button   */
if ('this_is' == /an_example/) {
  do_something();
} else {
  var a = b ? (c % d) : e[f];
}

So, how do I pass a callback function to the server; which returns the name, and call it. If there is another approach, I am open to that, of passing a callback function and acting upon it in the response set.

Thank you.

Off the top of my head, there are a couple of approaches I can think of. eval() is a possibility, but is generally considered something to avoid given the risk of running arbitrary JS code (ultimately this depends on who is providing the string which is being evaled).

I would recommend the following approach:

Create you functions as declarations on a basic JS object.

var Callbacks = {
   callback1: function(){ },
   callback2: function(){ }
};

Then, use the string returned from your AJAX call as a property indexer into your Callbacks object. I'm not familiar with YUI AJAX requests, but hopefully you get the idea:

var p_callback = function(){
   var local_callback = // parse response, get the callback method you want by name/string
   Callbacks[local_callback](); // providing arguments as needed, of course
};
YAHOO.util.Connect.asyncRequest('GET', p_parms, p_callback);

By using property accessors on your object you are assured that you are executing only your own callback code, instead of arbitrary JavaScript that may have been included in the response.