2015-09-09 43 views
0

我正在嘗試構建一個Web應用程序,用戶可以使用OpenLayers繪製功能,然後將它們保存爲下載或寫入服務器上的文件,我可以在需要時收集這些文件。到目前爲止,我對OL3位感到滿意。從閱讀周圍看來,AJAX是這樣做的,所以我設法在我的HMTL中包含一個按鈕,該按鈕運行一個運行php文件的函數來創建一個新文件。我很高興我設法得到一個空文本文件作爲開始。那麼如何讓該文件包含JSON信息?我想我需要將它從JS世界發送到PHP以某種方式?我看到一個使用jquery的答案,它通過發佈後發送數據,但我無法弄清楚如何在我的頁面上運行該腳本。使用AJAX保存JSON數據

的功能

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

回答

0

嘗試發送包含您的JSON對象到PHP文件的POST請求:

客戶端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); 
?> 
+0

你的代碼的工作,我幾乎沒有。但GEOJson文件的內容具有額外的斜槓加載函數loadXMLDoc()var geoJSON = new ol.format.GeoJSON(); var jsondata = geoJSON.writeFeatures(lyr_site.getSource()。getFeatures()); var xmlhttp = new XMLHttpRequest(); xmlhttp.open('POST','run.php',true); xmlhttp.setRequestHeader('Content-Type','application/json; charset = UTF-8'); xmlhttp.send(JSON.stringify(jsondata));' – Sethinacan

+0

額外的斜線似乎是因爲'.stringify',所以我刪除了它,並且我得到一個打開並具有屬性但沒有空間範圍的文件,即使該文件充滿了座標。 'xmlhttp.send(jsondata);' – Sethinacan

+0

該文件基本沒問題,但缺少以下這行,如果我手動添加它可以正常工作。 '「crs」:{「type」:「name」,「properties」:{「name」:「urn:ogc:def:crs:EPSG :: 3857」}},' – Sethinacan