웹 프로그래밍을 학습하며 구현한 프로젝트의 일부분
input_data.js
function input_data() { $.ajax({ type: "POST", url: './addData.php', dataType: 'json', data: createData(), complete : function(result) { //Add logic when complete } }); }
createData.js
function createData() { //Input your filepath let filepath = "./data.json"; let date = "2020-12-04"; let time = "03:23" let title = "Hello world!" let desc = "Coding is hard" var sendData = {path: filepath, date: date, time: time, title: title, description: desc}; return sendData; }
addData.php
<?php header("Content-Type: application/json"); $url = $_POST["path"]; $json_string = ""; $R = array(); //If file exist, read data from url if(file_exists($url)) { $json_string = file_get_contents($url); $R = json_decode($json_string, true); } $data = array(); $data["date"] = $_POST["date"]; $data["time"] = $_POST["time"]; $data["title"] = $_POST["title"]; $data["description"] = $_POST["description"]; array_push($R, $data); $data = json_encode($R); file_put_contents($url, $data); ?>
input_data 함수 실행 후의 data.json
[{"date":"2020-12-04","time":"03:23","title":"Hello world!","description":"Coding is hard"}]
data.json
[{"date":"2020-12-04","time":"03:23","title":"Hello world!","description":"Coding is hard"}, {"date":"2020-12-03","time":"05:33","title":"Hello json","description":"json is hard"}, {"date":"2020-12-02","time":"04:53","title":"Hello ajax!","description":"ajax is hard"}, {"date":"2020-12-04","time":"12:56","title":"Hello php!","description":"php is hard"}]
searchData.js
function searchData() { let date = "2020-12-04"; $.ajax({ type: "POST", url: './searchData.php', dataType: 'json', data: createSearchData(date), complete : function(result) { let arr = result.responseText.split('\n'); /* arr = []; */ } }); }
createSearchData.js
function createSearchData(date) { let pathname = "./data.json"; var sendData = {path: pathname, date: date}; return sendData; }
searchData.php
<?php header("Content-Type: application/json"); $url = $_POST["path"]; $json_string = ""; $R = array(); if(file_exists($url)) { $json_string = file_get_contents($url); $R = json_decode($json_string, true); } $data = array(); $data["date"] = $_POST["date"]; for ($i=0; $i < count($R); $i++) { if ($R[$i]["date"] == $data["date"]) { echo($R[$i]["date"].",".$R[$i]["time"].",".$R[$i]["title"].",".$R[$i]["description"]); echo "\n"; } } ?>
실행 후 arr의 값
arr = ["2020-12-04,03:23,Hello world!,Coding is hard",
"2020-12-04,12:56,Hello php,php is hard"]