使用AJAX保存JSON数据

时间:2015-09-09 15:31:02

标签: javascript php jquery json 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);
?>

1 个答案:

答案 0 :(得分:0)

尝试将包含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);
?>