С
Сергей74
PHP:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept');
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
$body = file_get_contents('php://input');
file_put_contents("users.json", $body);
echo "OK";
}
else if ($_SERVER['REQUEST_METHOD'] == "GET")
{
echo file_get_contents("users.json");
}
JavaScript:
var users = [];
$(document).ready(function()
{
function AddUser(userName, userRole, newId)
{
if (userName)
{
var newUserLine = $("<tr><td>" + userName + "</td><td>" + userRole + "</td><td><button class='btnDelete'>Удалить</button></td></tr>");
if (newId === undefined)
{
newId = (users.length>0)?users[users.length-1].id+1:1;
}
// users.push({id: newId, name:userName, role: userRole});
newUserLine.attr('userId', newId);
$("#tableUsers").find("tr").last().after(newUserLine);
newUserLine.find(".btnDelete").on('click', function()
{
var userLine = $(this).parent().parent();
var userId = parseInt(userLine.attr('userId'));
for(var i=users.length-1;i>=0;i--)
{
if (users[i].id === userId)
{
users.splice(i,1);
break;
}
}
userLine.remove();
});
return {id: newId, name:userName, role: userRole};
}
return null;
}
$("#editBox").find("input[type=button]").on('click', function()
{
var userName = $("#editBox").find("input[name=userName]").val();
var userRole = $("#editBox select[name=userRole]").val();
var newUser = AddUser(userName, userRole);
users.push(newUser);
});
$("#btnSave").on('click', function()
{
$.ajax({type:"POST",
url:"\server.php",
processData: false,
contentType: 'application/json',
data:JSON.stringify(users)})
.done(function(ret)
{
alert(ret);
})
.fail(function(err)
{
console.log(err);
});
});
$.ajax({type:"GET", url:"\server.php"})
.done(function(data)
{
users = JSON.parse(data);
for(var i=users.length-1;i>=0;i--)
{
AddUser(users[i].name, users[i].role, users[i].id);
}
});
function refreshUsersData()
{
$("#dataUsers").val(JSON.stringify(users));
setTimeout(refreshUsersData, 1000);
}
refreshUsersData();
});
GET