creating json object with variables

后端 未结 5 1266
清歌不尽
清歌不尽 2020-12-25 13:05

I am trying to create a json object from variables that I am getting in a form.

var firstName = $(\'#firstName\').val();
var lastName  = $(\'#lastName\').va         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-25 13:43

    You're referencing a DOM element when doing something like $('#lastName'). That's an element with id attribute "lastName". Why do that? You want to reference the value stored in a local variable, completely unrelated. Try this (assuming the assignment to formObject is in the same scope as the variable declarations) -

    var formObject = {
        formObject: [
            {
                firstName:firstName,  // no need to quote variable names
                lastName:lastName
            },
            {
                phoneNumber:phoneNumber,
                address:address
            }
        ]
    };
    

    This seems very odd though: you're creating an object "formObject" that contains a member called "formObject" that contains an array of objects.

提交回复
热议问题