使用javascript

时间:2017-01-16 09:52:45

标签: javascript php html json ajax

我有一个CSV文件,其中包含已转换为JSON的数据。现在我正试图找出如何将多个JSON对象发送到API JSON数组中。我目前正在使用ractive作为我的框架chocie。单击“发送JSON数据”按钮

将添加JSON对象

enter image description here

CSV到JSON转换

<html>

<body>

<?php 

    function csvToJson($fname) {
        if (!($fp = fopen($fname, 'r') )) {
            die("Can't open file");
        }

        $key = fgetcsv($fp, "1024", ",");

        $json = array();
            while ($row = fgetcsv($fp, "1024", ",")) {
                $json[] = array_combine($key, $row);
        }

        fclose($fp);

        foreach ( $json as $k=>$v ) {


            $json[$k]['dateRequested']     = $json[$k]['DATE']; 
            $json[$k]['assignedAgent']     = $json[$k]['AGENT'];
            $json[$k]['finalCompanyName']  = $json[$k]['COMPANY NAME'];
            $json[$k]['unitNumber']        = $json[$k]['UNIT'];
            $json[$k]['floorNumber']       = $json[$k]['FLOOR_LEVEL'];
            $json[$k]['buildingName']      = $json[$k]['BUILDING NAME'];
            $json[$k]['streetNumber']      = $json[$k]['NUMBER'];
            $json[$k]['streetName']        = $json[$k]['STREET'];
            $json[$k]['subdivisionName']   = $json[$k]['SUBDIVISION_COMPOUND_VILLAGE'];
            $json[$k]['barangayName']      = $json[$k]['BARANGAY'];
            $json[$k]['districtNum']       = $json[$k]['DISTRICT'];
            $json[$k]['cityMunicipality']  = $json[$k]['CITY_MUNICIPALITY'];
            $json[$k]['provinceName']      = $json[$k]['PROVINCE'];
            $json[$k]['region']            = $json[$k]['REGION'];
            $json[$k]['area']              = $json[$k]['AREA'];
            $json[$k]['longitude']         = $json[$k]['LONGITUDE'];
            $json[$k]['latitude']          = $json[$k]['LATITUDE'];
            $json[$k]['secRanking']        = $json[$k]['Sec Ranking'];
            $json[$k]['affiliate']         = $json[$k]['Affiliates'];
            $json[$k]['profiling']         = $json[$k]['Profiling'];
            $json[$k]['contactNumber']     = $json[$k]['CONTACT NUMBER'];
            $json[$k]['industry']          = $json[$k]['INDUSTRY']; 
            $json[$k]['amAssigned']        = $json[$k]['AM ASSIGNED'];
            $json[$k]['source']            = $json[$k]['SOURCE'];
            $json[$k]['gbu']               = $json[$k]['GBU'];
            $json[$k]['retention']         = $json[$k]['RETENTION'];
            $json[$k]['sec']               = $json[$k]['SEC'];
            $json[$k]['tier']              = $json[$k]['TIER'];
            $json[$k]['acqui']             = $json[$k]['ACQUI'];
            $json[$k]['finalReco']         = $json[$k]['FINAL RECO'];
            $json[$k]['remarksFindings']   = $json[$k]['FINAL REMARKS'];

            unset($json[$k]['DATE']);
            unset($json[$k]['AGENT']);
            unset($json[$k]['COMPANY NAME']);
            unset($json[$k]['UNIT']);
            unset($json[$k]['FLOOR_LEVEL']);
            unset($json[$k]['BUILDING NAME']);
            unset($json[$k]['NUMBER']);
            unset($json[$k]['STREET']);
            unset($json[$k]['SUBDIVISION_COMPOUND_VILLAGE']);
            unset($json[$k]['BARANGAY']);
            unset($json[$k]['DISTRICT']);
            unset($json[$k]['CITY_MUNICIPALITY']);
            unset($json[$k]['PROVINCE']);
            unset($json[$k]['REGION']);
            unset($json[$k]['AREA']);
            unset($json[$k]['LONGITUDE']);
            unset($json[$k]['LATITUDE']);
            unset($json[$k]['Sec Ranking']);
            unset($json[$k]['Affiliates']);
            unset($json[$k]['Profiling']);
            unset($json[$k]['CONTACT NUMBER']);
            unset($json[$k]['INDUSTRY']);
            unset($json[$k]['AM ASSIGNED']);
            unset($json[$k]['SOURCE']);
            unset($json[$k]['GBU']);
            unset($json[$k]['RETENTION']);
            unset($json[$k]['SEC']);
            unset($json[$k]['TIER']);
            unset($json[$k]['ACQUI']);
            unset($json[$k]['FINAL RECO']);
            unset($json[$k]['FINAL REMARKS']);

        }

        return json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

    }

 ?>



<?php
$json_data = csvToJson("lms.csv");
?>

Javascript

<div id="container">

</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/ractive/0.9.0-build-48/ractive.js"></script>


<script id="template" type="text/ractive">
     <a class="button cta" on-click="addData">Send JSON Data</a>
</script>

<script type="text/javascript">

var app = new Ractive({
    el       : '#container',
    template : '#template',
});

var proxy       = 'http://192.168.1.126/lms-dev-noel/proxy.php';
var endpoint    = 'account/leads/';
var rt          = 'POST';
var url         = proxy+'?endpoint='+endpoint+'&rt='+rt;

var lms_json    = <?php echo json_encode($json_data); ?>;

var jobjects = JSON.parse(lms_json);
console.log(jobjects)




app.on('addData', function(event) {
    $.ajax({
        type     : 'POST',
        url      : url,
        data     : jobjects,
        dataType : 'json',
        success  : function() {
            console.log(jobjects);
        },
        error    : function(error) {
            console.log('Error')
        }

    })

})


</script>

</body>

</html>

1 个答案:

答案 0 :(得分:0)

JSON只是一种符号,它不会改变任何东西。在解析了JSON字符串之后,您应该能够像往常一样在所需的键上推送对象/值。

jobjects['myKey1']['myKey2'].push({"key1":"value1", "key2":"value2"});

例如:

function edit() { // my edit code 
  var tr = $(this).closest("tr");
  var data = table.rows(tr).data();

  var rdata = data[0];
  alert(rdata[0]);
}

/// datatable code 
function createCustomisedDatatable(dataArray) {

 table= $('#example').dataTable({
    "data": dataArray,
    "order": [[0, "asc"]],
     "columnDefs": [{
      "targets": 0,
      "title": "ID",
      "searchable": false
    }, {
      "targets": 1,
      "title": "Name",
      "searchable": false
    }, {
      "targets": 2,
      "title": "button",
      "searchable": false,
       "render": function(data, type, row) {
       var returnHTML = CreateButtonDiv(data);
       return returnHTML;
       },
    }]
  });
}

/// here i am calling edit function 

 $('#DocListTable').on('click', '.edit', function () {

        edit();
    });

function CreateButtonDiv(data) {
return "<span class='edit fa fa-pencil-square-o' aria-hidden='true' id=" + data + " title='Edit' data-toggle='modal' data-target='#myModal' ></span>";
}

参考:here