When inside a function can I get it's parameters name/value?
I'm looking to turn those into an object that I can JSON.stringify() so I can pass it as data to an ajax call.
[EDIT] Thanks to others pointing me in the right direction I have a solution that dynamically creates parameters that match the webmethod with a client stub that matches the webmethod as well. This, I think, helps make things more readable.
[EDIT2] Took it a step further. Now the function name in javascript must match the name of the webmethod, and now you pass to it as the first param the page the webmethod exists on. It dynamically takes the client javascript function name, and that's what it's looking for now for the webmethod.
Here are the common methods that you create somewhere in your code:
function WebMethodCall(args) {
// in your stubs call this to get argname/value pairings in JSON form
var params = JSONArgs(args);
var fun = GetFunctionName(args);
// make a call to the webmethod via ajax using json
AjaxPostJSON(args[0] + "/" + fun, params, args);
}
function JSONArgs(args) {
var tmp = args.callee.toString().match(/\(.*?\)/)[0];
var argumentNames = tmp.replace(/[()\s]/g, '').split(',');
var param = new Object();
for (var i = 0; i < argumentNames.length; i++) {
param[argumentNames[i]] = args[i];
}
return JSON.stringify(param);
}
function GetFunctionName(args) {
var fName = args.callee.toString().match(/function ([^\(]+)/)[1]
return fName;
}
function AjaxPostJSON(url, data, args) {
var objGetData = new Object();
var fun = GetFunctionName(args);
var s = "On" + fun + "Success";
var f = "On" + fun + "Failure";
objGetData.url = url;
objGetData.type = "POST";
objGetData.data = data;
objGetData.contentType = "application/json; charset=utf-8";
objGetData.dataType = "json";
objGetData.success = window[s];
objGetData.error = window[f];
$.ajax(objGetData);
}
The stub where the parameter names should match the webmethod parameter names. The function name MUST also match the webmethod function name. Note that page is required to be the first parameter, but shouldn't be in your webmethod. It's simply used here to make the call correct: // function stub function GetData(page, id, name) { WebMethodCall(arguments); }
Notice the success and failure name patter of "On" + func_name + "Success"/"Failure". The usage:
function Button2_onclick() {
// call client side stub that matches the webmethod
GetData("Default.aspx", 8, "Bob");
}
// automatically registers these as success/error
function OnGetDataSuccess(data) {
alert(data.d);
}
function OnGetDataFailure(data) {
alert("failure");
}
The nice thing about this, I think, is that when I change/add parameters to my webmethod, it's so easy to just get the client javascript method and change the parameter names to match the webmethod and that's it.