- validateという名前の関数でcontという名前のローカル変数を宣言しました。
- 私はvalidateの内部から関数プロセスを呼び出しています。
- 関数を検証するための引数として文字列'cont'を送信しています。
- 文字列'cont'を使用するプロセス関数で、window['cont']のようなjavascriptローカル変数の値にアクセスしたいと思います。しかし、私は未定義になります。
- 私がやろうとしているのは、phpや$$の$GLOBALSのような変数にアクセスしようとしていることです。
これが私がしたことの例です。
<script>
function process(str)
{
alert(window[str]);
}
function validate()
{
var cont='once there lived a king named midas';
process('cont')
}
validate();
</script>
その理由は、ほとんどのフォームをajaxとして実行するためです。私はこのようなリクエスト文字列を作りたくありません。
var param = "command=insert&content=" + encodeURIComponent(cont);
こんな風にやりたいです。
var param = makeParam('command,[insert],content,(cont)');
makeparamで行うことは、正規表現を使用してキーと値のペアを抽出することです。したがって、(cont)から文字列contを取得し、それをwindow[cont]のようなウィンドウ変数に置き換えます。contには文字列'cont'があります。
では、変数の名前を文字列として使用して、変数の内容を取得するにはどうすればよいでしょうか。
だから私はphpの$$に相当するjavascriptを探しています
編集済み
(cont)内にあるcontを抽出するコードの一部。これは、()の間の文字列の内容が必要であることを意味します。
nxt = str[i+1].match(/\((.*)\)$/)
if(nxt)param += '=' + encodeURIComponent(window[nxt[1]]);
paramの内容は次のようになります
"command=insert&content=once there lived a king"
// assume that once there lived a king is encoded
編集。注2。
さらにいくつかの応答の後、これを追加するためにコードを編集しています。
私はphpで$GLOBALSのようにしようとしています。
$GLOBALSがローカル変数も保持できるかどうかは試していません。
そして、ローカルスコープが$GLOBALSに入らないことを学びました。
FelixKingのアップデートを読んだ後にアップデートしてください。
クエリ文字列をできるだけ単純に作成する関数を使用したいと思います。次のように。
var param = makeParam('command,insert,/title/,/keywords/,/description/,mode,[1],fckcontent,(cont)');
// if it is a text without // or () then the it is a straight key value pair. so i will do comment=insert.
//if it is /title/ then the key is title and its value is an input elements value with id as title so title=getElementById('title')
//if it is mode,[1] then mode is the key and 1 is its direct value//
//if it is fckcontent,(cont) then fckcontent is the key and cont is a javascript local variable which will contain html content from a WYSIWYG editor.
// a sample result will be
var param = "command=insert&keywords=somekeywords&description=somedescription&mode=1&fckcontent=<p>once there lived a king<p>
そしてcasablancaは、$GlOBALSにはローカルスコープ変数が含まれないと述べました。これはjavascriptでも同じです。それは正しい。