从本地存储将json数组追加到服务器上的json文件 [英] append json array from localstorage to json file on server

查看:345
本文介绍了从本地存储将json数组追加到服务器上的json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在localstorage中有一个json文件,我已经将该json分配给了具有javascript的变量,以便我可以使用php访问该文件.现在,我想将本地存储中的json文件的值附加到Web服务器中的json文件中.

I have a json file in localstorage and i have assigned that json to a variable with javascript so that i can access that with php. Now i want to append the values of that json file in my localstorage to the json file in my webserver.

这是示例javascript代码,我如何将localstorage json添加到变量

this is the sample javascript code how i added the localstorage json to variable

var lstore = ('data:application/json;charset=utf-8,' + encodeURIComponent(localStorage.regions));

现在,当我在javascript程序中运行window.open(lstore);时,我能够在浏览器窗口中看到完整的json数组.

now when i run window.open(lstore); in javascript program, i am able to see the complete json array in the browser window.

示例json数组看起来像这样

sample json array looks like this

[{
  "start":6,
  "end":8.2,
  "data":{
          "note":"ex1"
         }},
 { 
   "start":8.6,
   "end":12.2,
   "data":{
           "note":"rtt save"
          }},
 {
   "start":12.8,
   "end":16.2,
   "data":{
            "note": "rtl rss"
          }},

我想做的是从javascript调用php脚本,然后将localstorage json数据的值附加到Web服务器上的json文件中.但我也想检查服务器中的json文件中是否已经存在相同的开始"和结束"值,然后更新注释"值,否则添加新的开始",结束"和数据"值.

what i want to do is call a php script from javascript and then append the values of my localstorage json data to the json file on my webserver. But also i want to check if the same "start" and "end" values is already present in the json file in my server then just update the "note" value orelse add the new "start", "end" and "data" value.

推荐答案

首先,我们必须在这里了解3个核心概念:

First we have to understand 3 core concepts here:

  1. 您的JavaScript位于本地计算机(客户端)的浏览器中.
  2. 您的PHP在远程服务器(服务器端)上运行.
  3. Web应用程序的生命周期在请求中执行(每次您从浏览器发送/获取内容时).

开箱即用,您无法直接实时进行交流.但是,您可以将请求从javascript(客户端)发送到服务器(服务器端).

You can't directly communicate them in realtime out of the box. You can however, send a request from your javascript(clientside) to your server(serverside).

使用JQuery非常简单.在您的javascript文件中,您可以执行以下操作:

Using JQuery its quite easy. In your javascript file you do:

$.post('/yoursite.com/your_php_script.php', lstore);

这将向您的服务器发送一个AJAX请求.现在,在your_php_script.php中,您必须捕获该JSON的内容.

That will send an AJAX request to your server. Now in your_php_script.php you have to capture the content of that JSON.

$data = json_decode(file_get_contents('php://input'));

这将从您刚刚发送的请求的正文中读取JSON.

This reads the JSON from the body of the request you just sent.

您可能要使用Chrome开发工具,并查看网络"标签.在这里,您可以查看有关请求的所有信息.祝你好运!

You might want to use Chrome dev-tools and check out the network tab. There you can see all the information about the request. Good luck!

这篇关于从本地存储将json数组追加到服务器上的json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆