如何将数据从javascript发送到PHP脚本

时间:2014-03-03 08:54:42

标签: javascript php mysql

我在js中的代码(不起作用)将数据传输到PHP:

function codeAddress() {
  var address = document.getElementById('address').value;
  geocoder.geocode({ 'address': address}, function(results, status) {
   if (status == google.maps.GeocoderStatus.OK) {
  map.setCenter(results[0].geometry.location);
  var marker = new google.maps.Marker({
      map: map,
      position: results[0].geometry.location

  }); 


  var input = results[0].geometry.location; 

 var lat = input.lat(); 
 console.log(lat); 

/*var lat =  input.lat();
var longitude = input.lng();
document.getElementById("wypisz").innerHTML=lat;
request.open("GET", "address.php?lat=" + lat, true);

        //var url = "address.php?lat=latitude&lng =longitude";  


//document.getElementById("wypisz").innerHTML = results[0].geometry.location.lng;

*/



$.ajax({
    type: "GET",
    data: "lat=" + lat,
    url:"address.php",
    success: function(data) { console.log(data) }
})

} else {
  alert('Geocode was not successful for the following reason: ' + status);
}
 });

并将它们放入PHP文件中:

if(isSet($_GET['lat'])){
    echo "param good";
} else {
    echo "incorrect";   
}

当我print_r时,它总是显示空数组。 你能帮我改造吗?

这里有更多我的代码,这是我标记特定纬度和经度的地方:

 <div id="panel">
  Address :
  <input id="address" name = "address" type="textbox" value="Warszawa, Pol">

  <input type="button" value="wstaw" onclick="codeAddress()" >

</div>
<div id="map-canvas"></div>

在这里我发送信息到php文件:

<input type="submit" id = "ff" value="Send information">

2 个答案:

答案 0 :(得分:0)

尝试使用ajax调用,如:

$.ajax({
type:'GET'
url: "address.php?lat="+lat,
success:function(data){
}
});

答案 1 :(得分:0)

var req = new XMLHttpRequest(); 
req.open("GET", "adress.php", true);
req.onreadystatechange = function() {
    if(req.readyState != 4 || req.status != 200) 
        return; 
    console.log(req.responseText);
};
req.send("lat=" + lat);

这是一个非常简单的方法,如果你想在错误验证方面有所有的花里胡哨,我强烈建议你使用jquery和$ .get:

$.ajax({
        type: "GET",
        data: "lat=" + lat,
        url:"address.php",
        success: function(data) { console.log(data) }
    })