参见英文答案 >
How to pass JavaScript variables to PHP?12个
> Passing a JavaScript Value to a PHP Variable (With Limitation)3个
所以我知道Javascript是客户端的,PHP是服务器端的,这使事情复杂化,但我想知道如何去做.
> Passing a JavaScript Value to a PHP Variable (With Limitation)3个
所以我知道Javascript是客户端的,PHP是服务器端的,这使事情复杂化,但我想知道如何去做.
我的javascript代码(在HTML文件中)有一个数组,当用户点击我的提交按钮时,我希望页面通过该数组发送到我的PHP页面,然后将该日期转换为sql数据库.
有一个简单的方法来做到这一点?我的数组声明如下var markers = [];它只是代码的javascript部分中的变量.
我已经看了很多关于此的帖子,但是所有的解决方案都不适合我需要做的事情,或者需要对我现在能做的事情进行太多的改变.我对AJAX或JSON并不熟悉(不确定究竟是什么).
我的Javascript是:
var markers = []; function placeMarker(location) { var clickedLocation = new google.maps.LatLng(location); var name = document.getElementById("checkname").value; var description = document.getElementById("description").value; var marker = new google.maps.Marker({ position: location,map: map,title: name,// This may cause a problem when reloading and editing an existing tour // url was found at: http://biostall.com/adding-number-or-letters-to-google-maps-api-markers icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + markerId + '|FE6256|000000' }); marker.setMap(map); markers.push([markerId,name,marker.getPosition().lat(),marker.getPosition().lng(),description]); //alert("" + markers); markerId = markerId + 1; } google.maps.event.addListener(map,'click',function(event) { placeMarker(event.latLng); }); google.maps.event.addListener(marker,"click",function() { map.removeOverlay(marker); marker.setMap(map); }); } window.onload = function() { var form = document.getElementById('theform'); form.addEventListener('submit',function(){ var markersField = document.getElementById('markers'); markersField.value = JSON.stringify(markers); }); }
我的HTML是:
<form action="portal.PHP" method="post" id="theform"> <input type="hidden" id="markers" name="markers"> <button>Submit</button> </form>
$markers = json_decode($_POST['markers']); echo $markers;
解决方法
我假设您提交表单时已经重新加载了页面,并且您没有遇到任何问题.如果是这样,您可以为该数据添加隐藏字段,并将其添加到表单提交之前的字段中:
<form method="post" id="theform"> <!-- your existing form fields --> <input type="hidden" id="markers" name="markers"> <button>Submit</button> </form>
然后使用这个JavaScript
window.onload = function() { var form = document.getElementById('myform'); form.addEventListener('submit',function(){ var markersField = document.getElementById('markers'); var markers = [1,2,3]; markersField.value = JSON.stringify(markers); }); }
$markers = json_decode($_POST['markers']);