我有一個通過 websocket 與 JSON 物件通信的客戶端-服務器連接。我的服務器有幾個功能:
function FirstFunction(arg1, arg2) {
...
}
function SecondFuction(argOther) {
...
}
我的客戶端如何發送一個 JSON 物件,其中包含我要呼叫的函式的名稱以及引數,并使服務器呼叫該函式?像這樣的東西(偽代碼,不起作用)
data = {"method" : "FirstFunction", "params" : {"arg1" : 10, "arg2" : 20} }
result = data["mehod"](data.params.arg1, data.params.arg2)
我想這樣做的原因是因為我的客戶端使用 Python 和我的服務器 Javascript
uj5u.com熱心網友回復:
這聽起來像是一個很大的安全問題,但如果這對您來說不是問題,那么您可以這樣做:
function FirstFunction(arg1, arg2) { /* ... */ }
function SecondFunction(argOther) { /* ... */ }
const functions = {
FirstFunction,
SecondFunction
}
// You didn't specify how you receive the JSON
// so I'm just going to hard code it
const jsonString = `{"method" : "FirstFunction", "params" : {"arg1" : 10, "arg2" : 20} }`
function callFunction (json) {
const { method, params } = JSON.parse(json)
functions[method](...params)
}
callFunction(jsonString)
注意:示例區分大小寫
這里的技巧是將您想要提供給客戶端的功能作為可以使用字串訪問的物件的屬性分配。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/529553.html
下一篇:如何在python中重試
