簡體   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