0

パラメータ付きの URL を送信したいのですが、これらのパラメータは JavaScript を使用したフォームによって取得される値であり、JSON を使用してそれを実行したいのですが、デバッグ時に次のエラーが表示されます: Uncaught ReferenceError: name is not defined..

function recup()
{
var selectElmt = document.getElementById("name");
var selectcat = document.getElementById("msg");

var name = selectElmt.options[selectElmt.selectedIndex].value;
var msg  = selectcat.options[selectcat.selectedIndex].value;

}


    function go() {      // button send who call the function go

      var p_url="http://mysite.com/class?name=" + name + "&message=" + msg +  
                $.getJSON(p_url, {

            }).done(function( data ) {

                $.each(data, function (key, field) {
                   alert(field);
                });
            });  
                return false;
    }

値の name と msg を呼び出すときの構文エラーですが、それを修正する方法や go 関数でわかりません

4

2 に答える 2

0

2 つの変数は別の関数にあります

まあ、それはそれを説明しています。関数に対してローカルな変数は、別の関数からアクセスできません。

両方の関数で共有されるスコープで変数を定義する必要があります。これはグローバル スコープである可能性がありますが、グローバル変数の作成は避ける必要があります (グローバル変数はname既に存在するため、名前を持つことはできません)。

より高いスコープの変数に値を割り当てたい場合は、name = ...;代わりに を使用しvar name = ...;ます。

例:

(function() {
   // create a new scope so that we don't pollute the global scope

   // this variable can be accessed by both functions
   var answer; 

   function foo() {
       // don't use `var` here, otherwise you create a local variable which
       // shadows the variable with the same name in a higher scope
       answer = 42; 
   }

   function bar() {
       alert(answer);
   }

   foo();
   bar();
}());
于 2013-08-21T10:06:19.987 に答える