2014-03-04 48 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; 
});