Переход из localstorage, сохранение текста на сервер, Ajax и PHP (* Рабочий пример *)

#javascript #php

#javascript #php

Вопрос:

Чтобы перейти от супер-новичка к полу-новичку, я хотел бы прекратить использовать localStorage и начать сохранять данные на моем маленьком сервере в Hostgator.

Мне удалось выполнить эту работу, но я не уверен, правильно ли я это сделал.

В основном мое намерение здесь заключается в следующем:

  • Иметь независимые файлы .txt для каждого города.
  • Сделайте http-запрос, загрузите и отобразите содержимое .txt.
  • Редактирование содержимого пользователем.
  • Сделайте http POST-запрос, чтобы сохранить новое содержимое в том же файле .txt.

и вот моя проблема, чтобы сохранить в same .txt, мне пришлось сделать кучу «if», «else if». Я не верю, что это правильный способ достижения этой цели.

Код работает нормально, но как правильно? или, если у вас есть какие-либо предложения, пожалуйста, не стесняйтесь поделиться! Спасибо! 🙂

============—>>>
Рабочий пример здесь

HTML:

 <div id="main">
    <header id="choose">
        <button id="LA">Los Angeles</button>
        <button id="Chicago">Chicago</button>
        <button id="NY">New York</button><br>        
    </header>
    <div id="result">

        <p id="comment">choose your city</p>
        <input type="text" id="addComment">
       <button id="saveBTN">Save</button>
    </div>
</div>
  

JavaScript:

 let loadMytext, saveMyText2PHP,MyLoadedTXTItems
document.getElementById('choose').addEventListener('click', function(e){
if(event.target.id =='LA'){
   loadMytext = 'LosAngeles.txt'
   saveMyText2PHP = 'LosAngeles='
}else if(event.target.id =='Chicago'){
   loadMytext = 'Chicago.txt'
   saveMyText2PHP = 'Chicago='
}else if(event.target.id =='NY'){
   loadMytext = 'Ny.txt'
   saveMyText2PHP = 'Ny='}

var xhr = new XMLHttpRequest();    
xhr.open('GET', loadMytext, true);
  
xhr.onload = function(){        
    if(this.status==200){                        
        console.log(this.responseText)
        MyLoadedTXTItems = JSON.parse(this.responseText);  
        document.getElementById('comment').innerHTML = MyLoadedTXTItems[0].text
        document.getElementById('addComment').value = MyLoadedTXTItems[0].myValue
    }}

    xhr.send()

});

document.getElementById('saveBTN').addEventListener('click', function(){
    let myValue = document.getElementById('addComment').value
    
    var entry = {
    "text": MyLoadedTXTItems[0].text,
    "myValue": myValue
    }
    MyLoadedTXTItems[0] = entry
    
var data = saveMyText2PHP JSON.stringify(MyLoadedTXTItems);  
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
  if (xmlhttp.readyState==4 amp;amp; xmlhttp.status==200){
  
  setTimeout(function(){location.reload(true) }, 1000);
  }
}
xmlhttp.open("POST","save.php",true);        
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(data);        
})
  

php:

 <?php

if($_POST['LosAngeles']){
   $post_data = $_POST['LosAngeles'];
   $file = 'LosAngeles';
}else if($_POST['Chicago']){
   $post_data = $_POST['Chicago'];
   $file = 'Chicago';
}else if($_POST['Ny']){
   $post_data = $_POST['Ny'];
   $file = 'Ny';
}

if (!empty($post_data)) {     
  $filename = $file.'.txt';
  $handle = fopen($filename, "w");
fwrite($handle, $post_data);
fclose($handle);    
}
?>
  

Вы видите, тааак много сумасшедших, если!!! :O

Комментарии:

1. На сервер ничего не было отправлено. У вас есть xhr.send() внутри xhr.onload = function(){} . xhr.send() потребности приходят после xhr.onload = function(){} , и он должен отправить ваш FormData экземпляр. Также обратите внимание, что xhr.onload срабатывает, когда xhr.status === 200 amp;amp; xhr.readyState === 4 , поэтому в этом тестировании нет необходимости.

2. но как это может быть, @StackSlave — это рабочий пример :p

3. Ничего не было отправлено на сервер??? Нет, код работает, проблема в IFS!!!

Ответ №1:

Вот пример того, как будет выглядеть переход туда и обратно с использованием XMLHttpRequest . Не стесняйтесь повторно использовать мою библиотеку. Я использовал его для примера. Вы можете обратить внимание на код после // magic below except end load :

 //<![CDATA[
/* js/external.js */
let get, post, doc, htm, bod, nav, M, I, mobile, S, Q, hC, aC, rC, tC, shuffle, rand; // for use on other loads
addEventListener('load', ()=>{
get = (url, success, responseType = 'json', context = null)=>{
  const x = new XMLHttpRequest;
  const c = context || x;
  x.open('GET', url); x.responseType = responseType;
  x.onload = ()=>{
    if(success)success.call(c, x.response);
  }
  x.send();
  return x;
}
post = function(url, send, success, responseType ='json', context = null){
  const x = new XMLHttpRequest;
  const c = context || x;
  x.open('POST', url); x.responseType = responseType;
  x.onload = ()=>{
    if(success)success.call(c, x.response);
  }
  if(typeof send === 'object' amp;amp; send amp;amp; !(send instanceof Array)){
    if(send instanceof FormData){
      x.send(send);
    }
    else{
      const fd = new FormData;
      let s;
      for(let k in send){
        s = send[k];
        if(typeof s === 'object' amp;amp; s)s = JSON.stringify(s);
        fd.append(k, s);
      }
      x.send(fd);
    }
  }
  else{
    throw new Error('send argument must be an Object');
  }
  return x;
}
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
  let w = within || doc;
  return w.querySelector(selector);
}
Q = (selector, within)=>{
  let w = within || doc;
  return w.querySelectorAll(selector);
}
hC = function(node, className){
  return node.classList.contains(className);
}
aC = function(){
  const a = [].slice.call(arguments), n = a.shift();
  n.classList.add(...a);
  return aC;
}
rC = function(){
  const a = [].slice.call(arguments), n = a.shift();
  n.classList.remove(...a);
  return rC;
}
tC = function(){
  const a = [].slice.call(arguments), n = a.shift();
  n.classList.toggle(...a);
  return tC;
}
shuffle = array=>{
  let a = array.slice(), i = a.length, n, h;
  while(i){
    n = Math.floor(Math.random()*i--); h = a[i]; a[i] = a[n]; a[n] = h;
  }
  return a;
}
rand = (min, max)=>{
  let mn = min, mx = max;
  if(mx === undefined){
    mx = mn; mn = 0;
  }
  return mn Math.floor(Math.random()*(mx-mn 1));
}
// magic below except end load
const city = I('city'), ops = city.options, out = I('output');
city.onchange = ()=>{
  post('response.php', {city:ops[ops.selectedIndex].text}, resp=>{
    if(resp.city){
      out.textContent = resp.city;
    }
    else{
      // roundtrip failure - hacker
    }
  });
}
}); // end load  
 /* css/external.css */
*{
  box-sizing:border-box; font:22px Tahoma, Geneva, sans-serif; color:#000; padding:0; margin:0; overflow:hidden;
}
html,body,.main{
  width:100%; height:100%;
}
.main{
  background:#ccc; overflow-y:auto; padding:10px;
}
label{
  margin-right:4px;
}
select{
  border:0; border-radius:3px; cursor:pointer;
}  
 <!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
    <title>Title Here</title>
    <link type='text/css' rel='stylesheet' href='css/external.css' />
    <script src='js/external.js'></script>
  </head>
<body>
  <div class='main'>
    <label for='city'>City</label><select id='city'>
      <option>Seattle</option>
      <option>San Francisco</option>
      <option>New York</option>
      <option>Boston</option>
      <option>Chicago</option>
      <option>Philadelphia</option>
      <option>San Antonio</option>
    </select>
    <div id='output'></div>
  </div>
</body>
</html>  

Поскольку приведенный выше код отправляет на response.php , это может выглядеть как:

 <?php /* response.php */
$o = new StdClass;
if(isset($_POST['city'])){
  $city = $_POST['city'];
  if($city === 'Seattle' || $city === 'San Francisco' || $city === 'New York' || $city === 'Boston' || $city === 'Chicago' || $city === 'Philadelphia'){
    $o->city = $city;
  }
  else{
    // hacker
  }
}
echo json_encode($o);
?>
  

Комментарии:

1. Спасибо за ваш ответ. Позвольте мне проверить это !! 🙂