简体   繁体   English

使用AJAX保存JSON数据

[英]Saving JSON data using AJAX

I am trying to build a web app where users can use OpenLayers to draw features and then save them either as a download or write to a file on the server which I can collect when I need it. 我正在尝试构建一个Web应用程序,用户可以在其中使用OpenLayers绘制功能,然后将其保存为下载内容或写入服务器上的文件中,以便在需要时可以收集它们。 I am happy with the OL3 bit so far. 到目前为止,我对OL3感到满意。 From reading around it seems AJAX is the way to do this so I have managed to included a button in my HMTL which runs a function that runs a php file to create a new file.I was pretty happy that I managed to get an empty text file as a start. 通过阅读看来,AJAX是做到这一点的方法,因此我设法在HMTL中包含一个按钮,该按钮运行一个功能,该功能运行一个php文件来创建一个新文件。文件作为开始。 So how do I get that file to contain the JSON information? 那么,如何获取包含JSON信息的文件? I assume I need to send it from the JS world to PHP somehow? 我想我需要以某种方式将其从JS世界发送到PHP? I have seen a answer using jquery which sends data though post but I can't figure out how to run that script on my page. 我已经看到了使用jquery的答案,它通过发布发送数据,但是我不知道如何在页面上运行该脚本。

The Function 功能

function loadXMLDoc()
{
var xmlhttp=new XMLHttpRequest();

xmlhttp.open("GET","run.php",true);
xmlhttp.send();
}
</script>

The button 按钮

<button type="button" onclick="loadXMLDoc()">do something</button>
The PHP file (run.php)

<?php
$myfile = fopen("store/anothernewfile.geojson", "w") or die("Unable to open     file!");
$txt = ['lyr_site'];
fwrite($myfile, $txt);
fclose($myfile);
?>

Try sending a POST request that contains your JSON object to your PHP file: 尝试将包含JSON对象的POST请求发送到PHP文件:

Client-side Javascript: 客户端Javascript:

function loadXMLDoc() {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open('POST', 'run.php', true);
  xmlhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
  xmlhttp.send(JSON.stringify({ foo: 'Hey', bar: true}));
}

Server-side PHP: 服务器端PHP:

<?php
  $request_body = file_get_contents("php://input");
  $myfile = fopen("store/anothernewfile.geojson", "w") or die("Unable to open     file!");
  fwrite($myfile, $request_body);
  fclose($myfile);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM