繁体   English   中英

使用AJAX保存JSON数据

[英]Saving JSON data using AJAX

我正在尝试构建一个Web应用程序,用户可以在其中使用OpenLayers绘制功能,然后将其保存为下载内容或写入服务器上的文件中,以便在需要时可以收集它们。 到目前为止,我对OL3感到满意。 通过阅读看来,AJAX是做到这一点的方法,因此我设法在HMTL中包含一个按钮,该按钮运行一个功能,该功能运行一个php文件来创建一个新文件。文件作为开始。 那么,如何获取包含JSON信息的文件? 我想我需要以某种方式将其从JS世界发送到PHP? 我已经看到了使用jquery的答案,它通过发布发送数据,但是我不知道如何在页面上运行该脚本。

功能

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

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

按钮

<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);
?>

尝试将包含JSON对象的POST请求发送到PHP文件:

客户端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}));
}

服务器端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