繁体   English   中英

如何在PHP中使用jQuery变量

[英]How to use jQuery variable in PHP

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

在我的脚本中,我有变量“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代码(控制器)

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];
......
}

传递给jQuery.ajax的对象中的data属性是一个对象。

data : { direccion: direccion }

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

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;
    });
}

此外,您的代码中缺少检索到的数据,不要忘记将数据放入done函数中:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM