簡體   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