[英]How to Communicate between PHP and JavaScript
I wrote a JavaScript function to convert GeoJson data to WKT format. 我编写了一个JavaScript函数,将GeoJson数据转换为WKT格式。 It works when i get the input value in the javascript code directly.
当我直接在javascript代码中获得输入值时,它就可以工作。 But I don't know how to get the input from the php and send it back.
但是我不知道如何从php获取输入并将其发送回去。
Here is the php code: 这是PHP代码:
<?php
$geojson=file_get_contents("clipfeature.geojson");
$WKT = $_POST['wkt'];
echo ($WKT);
?>
So it gets geojson data from a file and I want to receive the converted WKT code from the Javascript function. 因此,它从文件获取geojson数据,我想从Javascript函数接收转换后的WKT代码。
Please help me finish the JavaScript Code: 请帮助我完成JavaScript代码:
function converttoWKT (){
$.ajax({
type: "GET",
url: "readJson.php",
contentType: "application/json"
}).done(function (data) {
var JSONObject = How to give the value from PHP to this Variable;
var coordinate = JSONObject.features[0].geometry.coordinates;
var type= JSONObject.features[0].geometry.type;
var coordinate1 = "";
var coordinate2 = "";
for (var i=0; i< coordinate[0].length; i++) {
coordinate1= coordinate[0][i][0]+" "+coordinate[0][i][1];
coordinate2=coordinate1+","+coordinate2;
}
var WKT= "\""+ type + "((" + coordinate2;
WKT=WKT.substring(0,WKT.length-1);
WKT=WKT+"))\""
sendback ( );
});
function sendback(){$.post("readJson.php",
{'wkt':How to send the value of var WKT back to php 'wkt'
});
}
Basically: 基本上:
var jsVar= "<? echo $myVariable_value_goes_in_here; ?>";
or, as mentioned above: 或者,如上所述:
var JSONObject = <? echo json_encode($WKT); ?>;
// this NEED TO BE json, otherwise syntax error in JS!
Since you already know your return data will be JSON, you can just use $.getJSON()
for convenience. 由于您已经知道返回数据将是JSON,因此为方便起见,可以只使用
$.getJSON()
。 This is a $.get()
request paired with JSON.parse()
. 这是一个与
JSON.parse()
配对的$.get()
请求。 With $.getJSON()
, the JSON is parsed on response. 使用
$.getJSON()
,将在响应时解析JSON。 To send the data back, just use use jQuery's $.post()
. 要将数据发送回去,只需使用jQuery的
$.post()
。
Here's an edited version of your code. 这是您代码的编辑版本。
function converttoWKT() {
$.getJSON('clipfeature.geojson', function(data) {
var coordinate = data.features[0].geometry.coordinates;
var type = data.features[0].geometry.type;
var coordinate1 = '';
var coordinate2 = '';
for(var i = 0; i < coordinate[0].length; i++) {
coordinate1 = coordinate[0][i][0] + ' ' + coordinate[0][i][1];
coordinate2 = coordinate1 + ',' + coordinate2;
}
var WKT = '"' + type + '((' + coordinate2;
WKT = WKT.substring(0, WKT.length - 1);
WKT = WKT + '))"'
sendback(WKT);
});
};
function sendback(data) {
$.post('readJson.php', {
'wkt': data
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.