[英]How to use jQuery variable in PHP
Im using a MVC in PHP and I have this script created in my form page to validate three text boxes. 我在PHP中使用MVC ,我在我的表单页面中创建了这个脚本来验证三个文本框。 When these three text boxes contain a value my php code in my controller asks Google Map Api for the closest directions based on the input of these three fields. 当这三个文本框包含一个值时,我的控制器中的php代码会根据这三个字段的输入向Google Map Api询问最近的方向。
In my script I have the variable "direccion" which is what I need to pass to the controller using PHP but im not sure how to accomplish this. 在我的脚本中,我有变量“direccion”,这是我需要使用PHP传递给控制器,但我不知道如何实现这一点。
Script Code (View) : 脚本代码(查看) :
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 Code (Controller) : PHP代码(控制器) :
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];
......
}
data
property in the object passed to jQuery.ajax is an object. 传递给jQuery.ajax的对象中的data
属性是一个对象。
data : { direccion: direccion }
Then you can access the value of direccion
in your controller as a request parameter. 然后,您可以在控制器中访问direccion
的值作为请求参数。
In the if
condition put your ajax request like 在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;
});
}
In addition the retrieved data are missing in your code, don't forget to put data in done function : 此外,您的代码中缺少检索到的数据,不要忘记将数据放入done函数中:
.done(function(){
var data = data;
});
To 至
.done(function(data){
var data = data;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.