简体   繁体   中英

Not able to pass multiple JSON objects to ajax query

I have the following JSON objects:

var algo, encrypt, nameOfRecord, configOutput = new Object();

algo = JSON.parse('{"algorithm" :"'+response.fieldConfigProperties.algorithmNames+'"}');
encrypt = JSON.parse('{"encryptionLevel" :"'+response.fieldConfigProperties.encryptionLevels+'"}');
nameOfRecord = JSON.parse('{"recordName" :"'+recordName+'"}');
configOutput = JSON.parse('{"outputConfiguration" :"'+outputConfiguration+'"}');

How do i pass all of them at once to my ajax jQuery?

This is my jquery

$.ajax({
        headers: { 
        'Accept': 'application/json',
        'Content-Type': 'application/json' },
        url:"/FeildConfigurationServlet",
        method:"POST",
        data: //WHAT SHOULD I PASS HERE
        dataType:"json",

        success:function(response){
                            console.log(JSON.stringify(response));
                            console.log('success /FeildConfigurationServlet')

                        } })

Any help is appreciated. Thanks:)

EDIT:

This is the rest service i have to call:

@RequestMapping(value = "/FeildConfigurationServlet", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
// writes a new field config details or update an already existing field
// configuration
protected @ResponseBody String feildConfigurationServlet(@RequestBody FieldConfigurationData fcd) {

    String algorithm = fcd.getAlgorithm();
    String encryptionLevel = fcd.getEncryptionLevel();
    String fieldValueToBeConfigured = fcd.getFieldValueToBeConfigured();
    String recordName = fcd.getRecordName();
    String outputConfiguration = fcd.getOutputConfiguration();



    String fileNameBigDataXML = CommonUtils.getConfigFolderPath()
            + "\\Config-XML\\tap-dap-anonymizer-configuration.xml";
    String dataReadFieldOutputConfig = null;
    String dataReadRecordStructure = null;
    try {
        dataReadFieldOutputConfig = readDataFromFile(
                CommonUtils.getConfigFolderPath() + "\\Config-XML\\field_output_config.xml");
        dataReadRecordStructure = readDataFromFile(
                CommonUtils.getConfigFolderPath() + "\\Config-XML\\record_structure.xml");

    } catch (IOException e) {
        e.printStackTrace();
    }

    // read data from bigdata XML and from fieldconfig XML
    String dataRead = null;
    try {
        dataRead = readDataFromFile(fileNameBigDataXML);
    } catch (IOException e) {
        e.printStackTrace();
    }
    // to append record sturcture(to get output under that fieldname)
    dataRead = appendRecordStructureForRecordType(dataRead, dataReadRecordStructure, recordName,
            fieldValueToBeConfigured);
    // manipulations for the data
    String finalDataForFieldOutputConfig = generateGenericFieldConfigStructure(dataReadFieldOutputConfig,
            fieldValueToBeConfigured, outputConfiguration, algorithm, encryptionLevel);
    // manipulated data whether to add or to update
    try {
        addOrUpdateFieldConfig(dataRead, fieldValueToBeConfigured, finalDataForFieldOutputConfig,
                fileNameBigDataXML, recordName);
    } catch (IOException e) {
        e.printStackTrace();
    }
    // sending response
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("success", true);
    return jsonObject.toString();
}

public static String appendRecordStructureForRecordType(String dataRead, String dataReadRecordStructure,
        String recordName, String fieldValueToBeConfigured) {

    dataReadRecordStructure = dataReadRecordStructure.replaceFirst("<dap-property-value></dap-property-value>",
            "<dap-property-value>" + fieldValueToBeConfigured + "_hash</dap-property-value>");
    String firstpart = dataRead.substring(0, dataRead.indexOf("<record-name>" + recordName + "</record-name>"));
    String lastPart = dataRead.substring(dataRead.indexOf("<record-name>" + recordName + "</record-name>"));
    String changeToAppend = lastPart.substring(0, lastPart.indexOf("</record-structure>")) + dataReadRecordStructure
            + lastPart.substring(lastPart.indexOf("</record-structure>"));
    String finaldataRead = firstpart + changeToAppend;
    return finaldataRead;

}

public static String generateGenericFieldConfigStructure(String dataReadFieldOutputConfig,
        String fieldValueToBeConfigured, String outputConfiguration, String algorithm, String encryptionLevel) {

    dataReadFieldOutputConfig = dataReadFieldOutputConfig.replaceFirst("<field-reference></field-reference>",
            "<field-reference>" + fieldValueToBeConfigured + "</field-reference>");
    dataReadFieldOutputConfig = dataReadFieldOutputConfig.replaceFirst(
            "<drop-original-field></drop-original-field>",
            "<drop-original-field>" + outputConfiguration + "</drop-original-field>");
    dataReadFieldOutputConfig = dataReadFieldOutputConfig.replaceFirst("<algorithm></algorithm>",
            "<algorithm>" + algorithm + "</algorithm>");

    dataReadFieldOutputConfig = dataReadFieldOutputConfig.replaceFirst(
            "<field-operation-name></field-operation-name>",
            "<field-operation-name>" + fieldValueToBeConfigured + "_hash</field-operation-name>");
    String firstData = dataReadFieldOutputConfig
            .substring(dataReadFieldOutputConfig.lastIndexOf("<operation-configuration>"));
    String data = dataReadFieldOutputConfig.substring(0,
            dataReadFieldOutputConfig.lastIndexOf("<operation-configuration>") - 1);
    firstData = firstData.replace("<algorithm></algorithm>", "<algorithm>" + encryptionLevel + "</algorithm>");
    dataReadFieldOutputConfig = data + firstData;
    return dataReadFieldOutputConfig;
}

public static void addOrUpdateFieldConfig(String dataRead, String fieldValueToBeConfigured,
        String finalDataForFieldOutputConfig, String fileNameBigDataXML, String recordName) throws IOException {
    if (dataRead.contains("<field-reference>" + fieldValueToBeConfigured + "</field-reference>")) {
        // to be updated
        int fieldReferenceIndex = dataRead
                .indexOf("<field-reference>" + fieldValueToBeConfigured + "</field-reference>");
        String firstPartdataRead = dataRead.substring(0, fieldReferenceIndex);
        String remainingPartdataread = dataRead.substring(fieldReferenceIndex - 1);
        // to be appended to remaining part
        String inbet = StringUtils.substringBetween(finalDataForFieldOutputConfig, "<field-operations>",
                "</field-operations>");
        // first and last index of field <field-operations>
        remainingPartdataread = remainingPartdataread.substring(0,
                remainingPartdataread.indexOf("<field-operations>")) + "<field-operations>" + inbet
                + remainingPartdataread.substring(remainingPartdataread.indexOf("</field-operations>"));
        dataRead = firstPartdataRead + remainingPartdataread;
        writeToFile(dataRead, fileNameBigDataXML);
        logger.debug("This is updating field config details : " + "writing field data to file : " + dataRead);
    } else {
        // for a new field config
        int recordReferenceIndex = dataRead.indexOf("<record-reference>" + recordName + "</record-reference>");
        String firstPartdataRead = dataRead.substring(0, recordReferenceIndex);
        String remainingPartdataread = dataRead.substring(recordReferenceIndex - 1);
        String LastPartBigData = remainingPartdataread.substring(0,
                remainingPartdataread.indexOf("</record-anonymizer-configuration>")) + finalDataForFieldOutputConfig
                + remainingPartdataread
                        .substring(remainingPartdataread.indexOf("</record-anonymizer-configuration>") - 1);
        dataRead = firstPartdataRead + LastPartBigData;
        writeToFile(dataRead, fileNameBigDataXML);
        logger.debug("This is writing new field config details : " + "writing field data to file : " + dataRead);
    }
}

I have to pass all the objects to this service. How do i do that?

UPDATE: I forgot to add this class

package com.entity;

public class FieldConfigurationData {

private String algorithm;
private String encryptionLevel;
private String fieldValueToBeConfigured;
private String recordName;
private String outputConfiguration;

public String getAlgorithm() {
    return algorithm;
}

public void setAlgorithm(String algorithm) {
    this.algorithm = algorithm;
}

public String getEncryptionLevel() {
    return encryptionLevel;
}

public void setEncryptionLevel(String encryptionLevel) {
    this.encryptionLevel = encryptionLevel;
}

public String getFieldValueToBeConfigured() {
    return fieldValueToBeConfigured;
}

public void setFieldValueToBeConfigured(String fieldValueToBeConfigured) {
    this.fieldValueToBeConfigured = fieldValueToBeConfigured;
}

public String getRecordName() {
    return recordName;
}

public void setRecordName(String recordName) {
    this.recordName = recordName;
}

public String getOutputConfiguration() {
    return outputConfiguration;
}

public void setOutputConfiguration(String outputConfiguration) {
    this.outputConfiguration = outputConfiguration;
}

@Override
public String toString() {
    return "FeildConfigurationData [algorithm=" + algorithm + ", encryptionLevel=" + encryptionLevel
            + ", fieldValueToBeConfigured=" + fieldValueToBeConfigured + ", recordName=" + recordName
            + ", outputConfiguration=" + outputConfiguration + "]";
}

}

You can create a new object which contains the JSON objects data

  $.ajax({
            headers: { 
            'Accept': 'application/json',
            'Content-Type': 'application/json' },
            url:"/FeildConfigurationServlet",
            method:"POST",
            data: {
             algo:algo,
             encrypt:encrypt,
             nameOfRecord:nameOfRecord,
             configOutput:configOutput 
            },
            dataType:"json",

            success:function(response){
                                console.log(JSON.stringify(response));
                                console.log('success /FeildConfigurationServlet')

                            } })

You can add multiple attributes to data, as you can read here . So you can simply use data: {"algo": algo, "encrypt": encrypt ...}

     var algo, encrypt, nameOfRecord, configOutput = new Object();
    var Obj = new Object();
    algo = JSON.parse('{"algorithm" :"'+response.fieldConfigProperties.algorithmNames+'"}');
    encrypt = JSON.parse('{"encryptionLevel" :"'+response.fieldConfigProperties.encryptionLevels+'"}');
    nameOfRecord = JSON.parse('{"recordName" :"'+recordName+'"}');
    configOutput = JSON.parse('{"outputConfiguration" :"'+outputConfiguration+'"}');

   Obj = {algo, encrypt, nameOfRecord, configOutput}

hope this helps...

First of all don't build JSON by hand, especially if you're going to parse it into an object anyway.

var data = {
    algorithm :response.fieldConfigProperties.algorithmNames,
    encryptionLevel: response.fieldConfigProperties.encryptionLevels,
    recordName: recordName,
    outputConfiguration: outputConfiguration,
    fieldValueToBeConfigured: 'some value'
};

When sending json you should set the content type to application/json, and pass you js data as json

$.ajax({
    url:"/FeildConfigurationServlet",
    method:"POST",
    data: JSON.stringify(data),
    contentType: 'application/json',
    dataType:"json",

    success:function(response){
        console.log(JSON.stringify(response));
        console.log('success /FeildConfigurationServlet')

    } 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM