JSON を介して Web サービスを呼び出す関数が多数ある大規模な Web アプリケーションに携わってきました。例えば:
/*...*/
refreshClientBoxes: function(customerNr) {
var request = {};
request.method = "getClientBoxes";
request.params = {};
request.params.customerNr = customerNr;
request.id = Math.floor(Math.random() * 101);
postObject(jsonURL, JSON.stringify(request), successClientBoxes);
},
/*...*/
「postObject」は、URL、データ、およびコールバックを受け取る関数です。
ご覧のとおり、すべてのメソッドでこのコードを作成する必要があります。
var request = {};
request.method = "getClientBoxes";
request.params = {};
request.params.customerNr = customerNr;
request.id = Math.floor(Math.random() * 101);
変更されるのは、呼び出すメソッドの名前と、渡すパラメーターの名前と値です。
したがって、呼び出すメソッドの名前とパラメーターの配列を受け取り、何らかのリフレクションを使用してリクエストパラメーターを構築し、リクエストを文字列化して返すメソッドを通じて、この努力を回避できる方法があるかどうか疑問に思っていました。
WS には、php + zend 1.12、JS の MVC フレームワーク、ember 0.95、および jQuery を使用しました。
編集1:あなたの答えに感謝します。私が欲しいのは、関数に渡すパラメーターの名前または渡した変数の名前を教えてくれる方法です。このようなもの:
var contructRequest = function (methodName, paramList) {
var request = {};
request.method = methodName;
request.params = {};
for(var i = 0; i < paramlist; i++){
/*some how get the paramName through reflection...so if i give a variable called customerNr this "for" add this new parameter to list of parameters like request.params.customerNr = customerNr whatever the variable name is or its value*/
}
request.params[paramName] = paramValue;
request.id = Math.floor(Math.random() * 101);
return request;
}