如何使用jQuery AJAX POST嵌套对象?

时间:2018-03-30 15:11:59

标签: javascript jquery ajax strongloop

您好我尝试将我在表单中插入的数据发送到我的API,但它在与其他模型的模型关系中使用如何获取表单的数据并插入数组中?当我尝试在不进行嵌套对象的情况下发送数据时,数据是在没有复合对象组织的情况下发送的,我最终找到了基于PHP和MVC的内容,我正在尝试做但不能用于Javascript,他们可以帮助我吗? / p>

My Structure API / POST。

{
  "idCompany": "string",
  "descriptionCompany": "string",
  "nameContactComercialCompany": "string",
  "phoneLandlineComercialCompany": "string",
  "cellphoneComercialCompany": "string",
  "cellphoneForMessageCompany": "string",
  "emailCompany": "string",
  "importObservationCompany": "string",
  "nameFantasyCompany": "string",
  "socialNameCompany": "string",
  "cpfCompany": "string",
  "cnpjCompany": "string",
  "stateRegistrationCompany": "string",
  "idCountyCompany": "string",
  "nfeStatusCompany": "string",
  "nfeExtendInfoCompany": "string",
  "nfeContactEmailCompany": "string",
  "accountingAccountCompany": "string",
  "businessAccountCompany": "string",
  "accountingChannelCompany": "string",
  "accountingSpeciesCompany": "string",
  "cashBalanceCompany": "string",
  "creditLimitCompany": "string",
  "invoiceMaturityCompany": "string",
  "billToDayCompany": "string",
  "registeredCompany": "string",
  "changedCompany": "string",
  "statusCompany": "string",
  "acceptTerms": "string",
  "id": "string",
  "channel": {
    "idChannel": "string",
    "descriptionChannel": "string",
    "registeredChannel": "string",
    "changedChannel": "string",
    "statusChannel": "string",
    "acceptTerms": "string",
    "id": "string",
    "species": {
      "idSpecies": "string",
      "descriptionSpecies": "string",
      "registeredSpecies": "string",
      "changedSpecies": "string",
      "statusSpecies": "string",
      "acceptTerms": "string",
      "id": "string"
    }
  },
  "special_price_for_products": {
    "productSellPriceCompany": "string",
    "taxShippingProductPriceCompany": "string",
    "currentBalanceOfProductPriceCompany": "string",
    "lastPurchaseOfProductPriceCompany": "0,00",
    "minimumStockOfProductPriceCompany": "0",
    "amountReservedOfProductPriceCompany": "0",
    "amountPendingOfProductPriceCompany": "0",
    "ammountBorrowedOfProductPriceCompany": "0",
    "registeredProductPriceCompany": "string",
    "changedProductPriceCompany": "string",
    "statusPriceCompany": "string",
    "acceptTerms": "string",
    "id": "string"
  },
  "tickets": {
    "beadGenerateTicket": "string",
    "detailsGenerateTicket": "string",
    "quantityPerBeadGenerateTicket": "0",
    "quantityGenerateTicket": "0",
    "initialTicketBeadGenerateTicket": "0",
    "initialBeadGenerateTicket": "0",
    "registeredGenerateTicket": "string",
    "changedGenerateTicket": "string",
    "statusGenerateTicket": "string",
    "acceptTerms": "string",
    "id": "string",
    "bead": {
      "idTicket": "string",
      "nameTicket": "string",
      "descriptionTicket": "string",
      "barCodeTicket": "string",
      "ncmCodeTicket": "string",
      "typeBeadTicket": "string",
      "priceFinalTicket": "0,00",
      "generatedTicket": "0",
      "quantityUsedTicket": "0",
      "quantitySellTicket": "0",
      "quantityPendingTicket": "0",
      "registeredTicket": "string",
      "changedTicket": "string",
      "statusTicket": "string",
      "acceptTerms": "string",
      "id": "string"
    }
  },
  "address": {
    "nameAddress": "string",
    "latAddress": "string",
    "lngAddress": "string",
    "numberAddress": "string",
    "complementAddress": "string",
    "neighborhoodAddress": "string",
    "cepAddress": "string",
    "cityAddress": "string",
    "stateAddress": "string",
    "id": "string",
    "title": {
      "idTitleStreet": "string",
      "descriptionTitleStreet": "string",
      "registeredTitleStreet": "string",
      "changedTitleStreet": "string",
      "statusTitleStreet": "string",
      "acceptTerms": "string",
      "id": "string"
    },
    "type": {
      "idTypeStreet": "string",
      "quickNameTypeStreet": "string",
      "informationsAboutTypeStreet": "string",
      "registeredTypeStreet": "string",
      "changedTypeStreet": "string",
      "statusTypeStreet": "string",
      "acceptTerms": "string",
      "id": "string"
    }
  }
}

我在API中的模型

{
  "name": "itapeCompanyNew",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "idCompany": {
      "type": "string",
      "required": true
    },
    "descriptionCompany": {
      "type": "string",
      "required": true
    },
    "nameContactComercialCompany": {
      "type": "string",
      "required": true
    },
    "phoneLandlineComercialCompany": {
      "type": "string",
      "required": true
    },
    "cellphoneComercialCompany": {
      "type": "string"
    },
    "cellphoneForMessageCompany": {
      "type": "string"
    },
    "emailCompany": {
      "type": "string"
    },
    "importObservationCompany": {
      "type": "string"
    },
    "nameFantasyCompany": {
      "type": "string",
      "required": true
    },
    "socialNameCompany": {
      "type": "string",
      "required": true
    },
    "cpfCompany": {
      "type": "string",
      "required": true
    },
    "cnpjCompany": {
      "type": "string",
      "required": true
    },
    "stateRegistrationCompany": {
      "type": "string"
    },
    "idCountyCompany": {
      "type": "string"
    },
    "nfeStatusCompany": {
      "type": "string",
      "required": true
    },
    "nfeExtendInfoCompany": {
      "type": "string"
    },
    "nfeContactEmailCompany": {
      "type": "string"
    },
    "accountingAccountCompany": {
      "type": "string"
    },
    "businessAccountCompany": {
      "type": "string"
    },
    "accountingChannelCompany": {
      "type": "string"
    },
    "accountingSpeciesCompany": {
      "type": "string"
    },
    "cashBalanceCompany": {
      "type": "string",
      "required": true
    },
    "creditLimitCompany": {
      "type": "string",
      "required": true
    },
    "invoiceMaturityCompany": {
      "type": "string"
    },
    "billToDayCompany": {
      "type": "string"
    },
    "registeredCompany": {
      "type": "string",
      "required": true
    },
    "changedCompany": {
      "type": "string"
    },
    "statusCompany": {
      "type": "string",
      "required": true
    },
    "acceptTerms": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "itapeStreetNew": {
      "type": "embedsOne",
      "model": "itapeStreetNew",
      "property": "address",
      "options": {
        "validate": true,
        "forceId": false
      }
    },
    "itapeCompanyProductPrice": {
      "type": "embedsOne",
      "model": "itapeCompanyProductPrice",
      "property": "special_price_for_products",
      "options": {
        "validate": true,
        "forceId": false
      }
    },
    "itapeChannelNew": {
      "type": "embedsOne",
      "model": "itapeChannelNew",
      "property": "channel",
      "options": {
        "validate": true,
        "forceId": false
      }
    },
    "itapeTicketGenerate": {
      "type": "embedsOne",
      "model": "itapeTicketGenerate",
      "property": "tickets",
      "options": {
        "validate": true,
        "forceId": false
      }
    }
  },
  "acls": [],
  "methods": {}
}

当我尝试发送此数据时,会发出此错误:

validation.js:122 Uncaught ReferenceError: species is not defined
    at HTMLFormElement.onFinished (*****.js:122)
    at HTMLFormElement.dispatch (2.2.4.min.js:3)
    at HTMLFormElement.r.handle (2.2.4.min.js:3)
    at Object.trigger (2.2.4.min.js:4)
    at n.fn.init.triggerHandler (2.2.4.min.js:4)
    at finishStep (jquery.steps.js:286)
    at HTMLAnchorElement.paginationClickHandler (jquery.steps.js:798)
    at HTMLAnchorElement.dispatch (2.2.4.min.js:3)
    at HTMLAnchorElement.r.handle (2.2.4.min.js:3)

我的AJAX请求

    var formData = {
        'idCompany': $('#idCompany').val(),
        'descriptionCompany': $('#descriptionCompany').val(),
        'nameContactComercialCompany': $('#nameContactComercialCompany').val(),
        'phoneLandlineComercialCompany': $('#phoneLandlineComercialCompany').val(),
        'cellphoneComercialCompany': $('#cellphoneComercialCompany').val(),
        'phoneLandlineScrapCompany': $('#phoneLandlineScrapCompany').val(),
        'emailCompany': $('#emailCompany').val(),
        'importObservationCompany': $('#importObservationCompany').val(),
        'nameFantasyCompany': $('#nameFantasyCompany').val(),
        'socialNameCompany': $('#socialNameCompany').val(),
        'cpfCompany': $('#cpfCompany').val(),
        'cnpjCompany': $('#cnpjCompany').val(),
        'stateRegistrationCompany': $('#stateRegistrationCompany').val(),
        'idCountyCompany': $('#idCountyCompany').val(),
        'nfeStatusCompany': $('#nfeStatusCompany').val(),
        'nfeExtendInfoCompany': $('#nfeExtendInfoCompany').val(),
        'nfeContactEmailCompany': $('#nfeContactEmailCompany').val(),
        'accountingAccountCompany': $('#accountingAccountCompany').val(),
        'businessAccountCompany': $('#businessAccountCompany').val(),
        address: [
            {
                'nameAddress': $('#addressCompany').val(),
                'numberAddress': $('#numberAddressCompany').val(),
                'complementAddress': $('#complementAddressCompany').val(),
                'neighborhoodAddress': $('#neighborhoodCompany').val(),
                'cepAddress': $('#cepCompany').val(),
                'cityAddress': $('#cityCompany').val(),
                'stateAddress': $('#stateCompany').val()
            }
        ],
        channel: [
            {
                'idChannel': $('#accountingChannelCompany').val()
            },
            species [
                {
                    'idSpecies': $('#accountingSpeciesCompany').val()
                }
            ]
        ],
        'cashBalanceCompany': $('#cashBalanceCompany').val(),
        'creditLimitCompany': $('#creditLimitCompany').val(),
        'invoiceMaturityCompany': $('#invoiceMaturityCompany').val(),
        'billToDayCompany': $('#billToDayCompany').val(),
        'registeredCompany': $('#registeredCompany').val(),
        'changedCompany': $('#changedCompany').val(),
        'statusCompany': $('#statusCompany').val(),
        'acceptTerms': $('#acceptTerms').val()
    };

    // Go Home Redirect
    $("#goHomeAuthenticated").click(function () { 
        $.ajax({
            data: formData,
            type: "POST",
            dataType: "JSON",
            url: 'https://****-api.herokuapp.com/api/***CompanyNews',
            success: function (response) {
                // Disabled Button After Send
                $("#goHomeAuthenticated").addClass("disabled");
                $("#undoRegisterAuthenticated").addClass("disabled");
                $("#redirectAuthenticated").addClass("disabled");

                // Success Dialog
                var placementFrom = "top";
                var placementAlign = "center";
                var colorName = "bg-light-green";

                // Set Options For Success Dialog
                showNotification(colorName, null, placementFrom, placementAlign);

                // Start New Success Dialog
                function showNotification(colorName, text, placementFrom, placementAlign, animateEnter, animateExit) {
                    if (colorName === null || colorName === '') { colorName = 'bg-black'; }
                    if (text === null || text === '') { text = 'Autenticado com sucesso! Em alguns segundos você sera redicionado...'; }
                    if (animateEnter === null || animateEnter === '') { animateEnter = 'animated fadeInDown'; }
                    if (animateExit === null || animateExit === '') { animateExit = 'animated fadeOutUp'; }
                    var allowDismiss = true;

                    // Start Modern Structure For Success Dialog Based In Material
                    $.notify({
                        message: text
                    }, {
                            type: colorName,
                            allow_dismiss: allowDismiss,
                            newest_on_top: true,
                            z_index: 1050,
                            timer: 380,
                            placement: {
                                from: placementFrom,
                                align: placementAlign
                            },
                            animate: {
                                enter: animateEnter,
                                exit: animateExit
                            },
                            template: '<div data-notify="container" class="bootstrap-notify-container alert alert-dismissible {0} ' + (allowDismiss ? "p-r-35" : "") + '" role="alert">' +
                                '<button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button>' +
                                '<span data-notify="icon"></span> ' +
                                '<span data-notify="title">{1}</span> ' +
                                '<span data-notify="message">{2}</span>' +
                                '<div class="progress" data-notify="progressbar">' +
                                '<div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' +
                                '</div>' +
                                '<a href="{3}" target="{4}" data-notify="url"></a>' +
                                '<a href="{3}" target="{4}" data-notify="url"></a>' +
                                '</div>'
                        }
                    );
                }

                // Redirect Client After Close Success Dialog
                window.setTimeout(function () {
                    window.location.href = '/';
                }, 5000);
            },
            error: function(failed) {
                // Load Options For Notification
                var placementFrom = "top";
                var placementAlign = "center";
                var colorName = "bg-red";

                // Set Options For Notification
                showNotification(colorName, null, placementFrom, placementAlign);

                // Start New Notification
                function showNotification(colorName, text, placementFrom, placementAlign, animateEnter, animateExit) {
                    if (colorName === null || colorName === '') { colorName = 'bg-black'; }
                    if (text === null || text === '') { text = 'Ocorreu um erro ao autenticar seu formulário, por favor atualize a página e tente novamente. Se erro persistir contate seu supervisor!'; }
                    if (animateEnter === null || animateEnter === '') { animateEnter = 'animated fadeInDown'; }
                    if (animateExit === null || animateExit === '') { animateExit = 'animated fadeOutUp'; }
                    var allowDismiss = true;

                    // Start Modern Structure For Notification Based In Material
                    $.notify({
                        message: text
                    }, {
                            type: colorName,
                            allow_dismiss: allowDismiss,
                            newest_on_top: true,
                            timer: 600,
                            placement: {
                                from: placementFrom,
                                align: placementAlign
                            },
                            animate: {
                                enter: animateEnter,
                                exit: animateExit
                            },
                            template: '<div data-notify="container" class="bootstrap-notify-container alert alert-dismissible {0} ' + (allowDismiss ? "p-r-35" : "") + '" role="alert">' +
                                '<button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button>' +
                                '<span data-notify="icon"></span> ' +
                                '<span data-notify="title">{1}</span> ' +
                                '<span data-notify="message">{2}</span>' +
                                '<div class="progress" data-notify="progressbar">' +
                                '<div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' +
                                '</div>' +
                                '<a href="{3}" target="{4}" data-notify="url"></a>' +
                                '<a href="{3}" target="{4}" data-notify="url"></a>' +
                                '</div>'
                        }
                    );
                }
            }
        });
    });

感谢您的帮助!!!

1 个答案:

答案 0 :(得分:0)

您遇到语法错误,导致JSON无效:

channel: [
    {
        'idChannel': $('#accountingChannelCompany').val()
    },
    species [
        {
            'idSpecies': $('#accountingSpeciesCompany').val()
        }
    ]
]

species数组中删除channel