使用JSON语法将参数作为值发送

send parametres as values using JSON syntax

本文关键字:参数 JSON 语法 使用      更新时间:2023-09-26

我想发送一个带有parameters的url,这些parameters是由带有javascript的表单获取的值,我想使用JSON来完成它,但当我调试时,我看到了这个错误:Uncaught ReferenceError:名称未定义。。

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函数

中修复它

如果出现两个错误,右大括号和加号,代码应该是:

var msg = "hello"; // i just simplified the value 
var name  = "test";
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;
}

更新:您需要将名称和消息设为全局:

var name, msg;
function recup() {
    var selectElmt = document.getElementById("name");
    var selectcat = document.getElementById("msg");
    name = selectElmt.options[selectElmt.selectedIndex].value;
    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;
}

和CCD_ 1需要在CCD_ 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();
}());