duancuisan2503 2018-03-14 22:54
浏览 90

如何基于登录用户以HTML格式显示JSON数据

I have a form in which user logs in and the data gets saved in a JSON dynamically. All that is working, but I want only that JSON data to be displayed which contains the email id of the logged in user which is set in session. Here is the script which creates the JSON: `

var g_objJSON = [];

        /** setJSON - Create JSON object
        * Returns - Nothing
        **/
    function setJSON() {
        //alert($(this).data('session-name'));
            var v_aJSON = [];
            var v_hObject = {};
            var v_hTempHash = {};

            var v_sKey = '<?php echo (isset($_SESSION['userEmail'])) ? $_SESSION['userEmail'] : ''; ?>';
            console.log(v_sKey);
            var x = document.getElementsByClassName('product-description')
            for (var i = 0; i < x.length; i++) {
                x[i].addEventListener("click", function(){

                    var selectedEl = document.querySelector(".selected");
                    if(selectedEl){
                        //selectedEl.classList.remove("selected");
                    }
                    //this.classList.add("selected");
                    alert('in addEventListener: ' + $(this).data('name'));
                    var v_sValue = $(this).data('name');
                    alert('event name : ' + v_sValue);
                    try {
                        v_hObject[v_sKey] = v_sValue;
                        if (g_objJSON == undefined) {
                            v_aJSON.push(v_hObject);
                        } else {
                            v_hTempHash = mergeHashOb(g_objJSON[0], v_hObject);
                            v_aJSON.push(v_hTempHash);
                        }
                        g_objJSON = v_aJSON;
                        alert("Events JSON created!");
                        for (var item in g_objJSON[0]) {
                            console.log("Email: " + item + "
Location: " +   g_objJSON[0][item]);
                            $.ajax({
                            url: 'json-2.php',
                            type: 'POST',
                            data: {json: JSON.stringify(g_objJSON)},
                            dataType: 'json'
                        });
                        }

                    } catch (x) {
                            alert(x.message);
                    }
                }, false);;
            }
    }
    /** mergeHashOb - Merge a new JSON object with the global JSON object
               * @prm_hObj - Existing Hash object
               * @prm_hObj2 - New Hash object
               * Returns - A new Hash object contains the merged Hash objects
               **/
               function mergeHashOb(prm_hObj, prm_hObj2) {
                       var v_hObj = {};
                       for (var item in prm_hObj) { 
                               v_hObj[item] = prm_hObj[item]; 
                       }
                       for (var item in prm_hObj2) { 
                               v_hObj[item] = prm_hObj2[item]; 
                       }
                       return v_hObj;
               }

`

json-2.php: `

<?php
    // let's parse this right away
    $json = json_decode($_POST['json']);

    /* sanity check */
    if ($json != null)
    {
      // parse the file contents to json
      $fileContents = file_get_contents('event_data.json');
      $parsedJson = json_decode($fileContents);

      if ($parsedJson === null) {
        // it's either the file contains bad json or it is empty (tested with 7.1)
        $parsedJson = array();
      }

      // append your new data to the parsed json
      // I'm assuming the $_POST['json'] returns a stringified array, I'll take the first element and append it.
      $parsedJson[] = $json[0];
      // now write to the file
      $file = fopen('event_data.json','w'); // note that we're writing, not appending.
      // write to file the json_encoded $parsedJson
      fwrite($file, json_encode($parsedJson));
      fclose($file);
    }
    else
    {
      // handle the error 
    }
?>

`

event_data.json: [{"charlie@gmail.com":"Finding Accomodation"},{"charlie@gmail.com":"Money Matters"},{"charlie@gmail.com":"Pathways to Deakin"},{"_empty_":"Finding Accomodation"},{"vrishty.garg@deakin.edu.au":"Finding Accomodation"},{"vrishty.garg@deakin.edu.au":"Finding Accomodation"},{"charlie@gmail.com":"Finding Accomodation"}]

So, I want only those arrays displayed which contains the key as logged in user, say charlie@gmail.com at a time, not all of the above.

Function of creating table: `

$(document).ready(function(){
  //alert('inside document.ready');
  $.getJSON("event_data.json", function (data) {
    //alert('in each function of getJSON()');

                    var arrItems = [];      // THE ARRAY TO STORE JSON ITEMS.
                    $.each(data, function (index, value) {
                      arrItems.push(value);       // PUSH THE VALUES INSIDE THE ARRAY.
                    });

                    // EXTRACT VALUE FOR TABLE HEADER.
                   var col = [];
                    for (var i = 0; i < arrItems.length; i++) {
                        for (var key in arrItems[i]) {
                            if (col.indexOf(key) === -1) {
                                col.push(key);
                            }
                        }
                    }

                    // CREATE DYNAMIC TABLE.
                    var table = document.createElement("table");
                    //var button = document.createElement("button");

                    // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

                    var tr = table.insertRow(-1);                   // TABLE ROW.

                    for (var i = 0; i < col.length; i++) {
                        var th = document.createElement("th");      // TABLE HEADER.
                        th.innerHTML = col[i];
                        tr.appendChild(th);
                    }

                    // ADD JSON DATA TO THE TABLE AS ROWS.
                    for (var i = 0; i < arrItems.length; i++) {

                        tr = table.insertRow(-1);

                        for (var j = 0; j < col.length; j++) {
                            var tabCell = tr.insertCell(-1);
                            tabCell.innerHTML = arrItems[i][col[j]];
                        }
                    }

                    // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
                    var divContainer = document.getElementById("showData");
                    //divContainer.innerHTML = "";
                    divContainer.appendChild(table);
                    //divContainer.appendChild(button);
                });
});

`

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 keil的map文件中Image component sizes各项意思
    • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
    • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
    • ¥15 划分vlan后,链路不通了?
    • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
    • ¥15 Vue3 大型图片数据拖动排序
    • ¥15 Centos / PETGEM
    • ¥15 划分vlan后不通了
    • ¥20 用雷电模拟器安装百达屋apk一直闪退
    • ¥15 算能科技20240506咨询(拒绝大模型回答)