2014-03-04 50 views
4

在PHP中使用MVC Im我在表单页面中创建了此脚本以验证三个文本框。当这三个文本框中包含一个值时,我的控制器中的我的php代码会根据这三个字段的输入向Google Map Api询问最接近的方向。如何在PHP中使用jQuery变量

在我的脚本中,我有变量“direccion”,这是我需要传递给控制器​​使用PHP,但我不知道如何做到这一点。

脚本代码(查看)

jQuery(document).ready(function() { 

    var direccion=""; 
    var flag = false; 
    jQuery(".validation").change(function() { 
     flag = true; 
     jQuery(".validation").each(function() { 
      if (jQuery(this).val().trim() == "") { 
       alert("false"); 
       flag = false; 
      } 
     }); 
     if (flag==true) { 

      var calle = jQuery("#ff_elem295").val(); 
      var municipio = jQuery("#id_municipio option:selected").text(); 
      var provincia = jQuery("#id_provincia option:selected").text();    

      direccion = calle +","+ municipio +","+ provincia; 
      direccion = direccion.replace(/\s/g,'+'); 
      //alert(direccion); 
     }  
}); 

jQuery.ajax({ 
      url: "index.php?option=com_cstudomus&controller=saloninmobiliarios&task=calcularDistancias", 
      data : direccion, 
      dataType : 'html' 
     }).done(function(){ 
       var data = data; 
     }); 
}); 

PHP代码(控制器):在传递给jQuery.ajax对象

function calcularDistancias(){ 

    $valor = JRequest::getVar('direccion'); 

    $url = 'http://maps.googleapis.com/maps/api/geocode/json?address='. $valor .'&sensor=false'; 

    $data = file_get_contents($url); 

    $data_array = json_decode($data,true); 

    $lat = $data_array[results][0][geometry][location][lat]; 
    $lng = $data_array[results][0][geometry][location][lng]; 
...... 
} 
+0

我想你需要使用ajax ..? – Naruto

+0

是的,多数民众赞成我想要做的,我通过变量“direccion”,但我不知道如何选择使用PHP这个变量,并在我的PHP函数中使用它 – PLATANIUM

回答

4

data属性是一个对象。

data : { direccion: direccion } 

然后,您可以在控制器中访问direccion的值作为请求参数。

+1

他必须设置'type'选项'POST '以及如果他想通过数据作为'POST' – hindmost

+0

我删除POST的东西,并写下更一般的 –

+0

@RobinWebdev当你说请求参数时,你指的是什么?像$ _GET一样? – PLATANIUM

1

if条件把你的Ajax请求喜欢

if(flag == true) { 
    jQuery.ajax({ 
     url: "index.php?option=com_cstudomus&controller=saloninmobiliarios&task=calcularDistancias", 
     data : {direction : direccion}, 
     dataType : 'html' 
    }).done(function(){ 
      var data = data; 
    }); 
} 
0

另外检索的数据丢失在代码中,不要忘了把数据中完成的功能:

.done(function(){ 
    var data = data; 
}); 

.done(function(data){ 
    var data = data; 
});