0

我得到一个带有地理定位 JavaScript 的数组,然后我想通过 ajax 将此数组传递给一个 php 脚本来处理它并返回一个处理过的数组。不幸的是,传递给 php 的数组似乎总是 NULL,我不知道为什么。

我的 JavaScript/jQuery:

dataArray = [];
        var lat = pos.coords.latitude;
        dataArray.push({'lat':lat});
        var lon = pos.coords.longitude;
        dataArray.push({'lon':lon});
        var identifier = 'ajax';
        dataArray.push({'identifier':identifier});
        console.debug(dataArray);

        $.ajax({
                async:   true,
                type:        'post',
                cache:       false,
                url:         'custom.php',
                data:        {myJson: dataArray},
                dataType   : 'json',
                success: function(data){
                    console.debug(data);
                    var json = $.parseJSON(data);
                    console.debug(json);
                    alert(json);
                }
        });

我的PHP:

$JSArray['array'] = json_decode($_POST['myJson'], true);
$_SESSION['jsonArray'] = $JSArray['array'];
var_dump($_SESSION);

结果总是["jsonArray"]=> NULL

4

2 回答 2

0

试试这个。这个对我有用

 (function($){
if(navigator.geolocation){return;}
var domWrite = function(){
        setTimeout(function(){
            throw('document.write is overwritten by geolocation shim. This method is incompatible with this plugin');
        }, 1);
    },
    id = 0
;
var geoOpts = $.webshims.cfg.geolocation.options || {};
navigator.geolocation = (function(){
    var pos;
    var api = {
        getCurrentPosition: function(success, error, opts){
            var locationAPIs = 2,
                errorTimer,
                googleTimer,
                calledEnd,
                endCallback = function(){
                    if(calledEnd){return;}
                    if(pos){
                        calledEnd = true;
                        success($.extend({timestamp: new Date().getTime()}, pos));
                        resetCallback();
                        if(window.JSON && window.sessionStorage){
                            try{
                                sessionStorage.setItem('storedGeolocationData654321', JSON.stringify(pos));
                            } catch(e){}
                        }
                    } else if(error && !locationAPIs) {
                        calledEnd = true;
                        resetCallback();
                        error({ code: 2, message: "POSITION_UNAVAILABLE"});
                    }
                },
                googleCallback = function(){
                    locationAPIs--;
                    getGoogleCoords();
                    endCallback();
                },
                resetCallback = function(){
                    $(document).unbind('google-loader', resetCallback);
                    clearTimeout(googleTimer);
                    clearTimeout(errorTimer);
                },
                getGoogleCoords = function(){
                    if(pos || !window.google || !google.loader || !google.loader.ClientLocation){return false;}
                    var cl = google.loader.ClientLocation;
                    pos = {
                        coords: {
                            latitude: cl.latitude,
                            longitude: cl.longitude,
                            altitude: null,
                            accuracy: 43000,
                            altitudeAccuracy: null,
                            heading: parseInt('NaN', 10),
                            velocity: null
                        },
                        //extension similiar to FF implementation
                        address: $.extend({streetNumber: '', street: '', premises: '', county: '', postalCode: ''}, cl.address)
                    };
                    return true;
                },
                getInitCoords = function(){
                    if(pos){return;}
                    getGoogleCoords();
                    if(pos || !window.JSON || !window.sessionStorage){return;}
                    try{
                        pos = sessionStorage.getItem('storedGeolocationData654321');
                        pos = (pos) ? JSON.parse(pos) : false;
                        if(!pos.coords){pos = false;} 
                    } catch(e){
                        pos = false;
                    }
                }
            ;

            getInitCoords();

            if(!pos){
                if(geoOpts.confirmText && !confirm(geoOpts.confirmText.replace('{location}', location.hostname))){
                    if(error){
                        error({ code: 1, message: "PERMISSION_DENIED"});
                    }
                    return;
                }
                $.ajax({
                    url: 'http://freegeoip.net/json/',
                    dataType: 'jsonp',
                    cache: true,
                    jsonp: 'callback',
                    success: function(data){
                        locationAPIs--;
                        if(!data){return;}
                        pos = pos || {
                            coords: {
                                latitude: data.latitude,
                                longitude: data.longitude,
                                altitude: null,
                                accuracy: 43000,
                                altitudeAccuracy: null,
                                heading: parseInt('NaN', 10),
                                velocity: null
                            },
                            //extension similiar to FF implementation
                            address: {
                                city: data.city,
                                country: data.country_name,
                                countryCode: data.country_code,
                                county: "",
                                postalCode: data.zipcode,
                                premises: "",
                                region: data.region_name,
                                street: "",
                                streetNumber: ""
                            }
                        };
                        endCallback();
                    },
                    error: function(){
                        locationAPIs--;
                        endCallback();
                    }
                });
                clearTimeout(googleTimer);
                if (!window.google || !window.google.loader) {
                    googleTimer = setTimeout(function(){
                        //destroys document.write!!!
                        if (geoOpts.destroyWrite) {
                            document.write = domWrite;
                            document.writeln = domWrite;
                        }
                        $(document).one('google-loader', googleCallback);
                        $.webshims.loader.loadScript('http://www.google.com/jsapi', false, 'google-loader');
                    }, 800);
                } else {
                    locationAPIs--;
                }
            } else {
                setTimeout(endCallback, 1);
                return;
            }
            if(opts && opts.timeout){
                errorTimer = setTimeout(function(){
                    resetCallback();
                    if(error) {
                        error({ code: 3, message: "TIMEOUT"});
                    }
                }, opts.timeout);
            } else {
                errorTimer = setTimeout(function(){
                    locationAPIs = 0;
                    endCallback();
                }, 10000);
            }
        },
        clearWatch: $.noop
    };
    api.watchPosition = function(a, b, c){
        api.getCurrentPosition(a, b, c);
        id++;
        return id;
    };
    return api;
})();

$.webshims.isReady('geolocation', true);
    })(jQuery);


     jQuery(window).ready(function(){ 

navigator.geolocation.getCurrentPosition(successCallback,errorCallback,{timeout:10000});

function successCallback(pos) {

    $('#localstore').
    load("geo?latitude="+ pos.coords.latitude +"&longitude=" + pos.coords.longitude, function() 
    {
        $('#storefinder').hide();
        $('#localstore').show();
    });

}
function errorCallback(pos) {
    /*      
    $('#storefinder').show();
    $('#localstore').hide();
    */
}



});
于 2013-02-25T14:25:21.443 回答
0

您的脚本可能在多个方面失败。我会测试每个步骤,看看它在哪里失败(通过一次注释掉一个回显语句):

echo $_POST['myJson'];
$JSArray['array'] = json_decode($_POST['myJson'], true);
//echo $JSArray['array'];
$_SESSION['jsonArray'] = $JSArray['array'];
//var_dump($_SESSION);

此外,您的 ajax 调用应该不包含alert(data)parseJSON,因为服务器没有发送回 JSON,它只是回显一个 var_dump:

$.ajax({
                async:   true,
                type:        'post',
                cache:       false,
                url:         'custom.php',
                data:        {myJson: dataArray},
                dataType   : 'html', // change back to json when you send json from server
                success: function(data){
                    console.debug(data);
                    //var json = $.parseJSON(data);
                    //console.debug(json);
                    //alert(json);
                    alert(data);
                }
        });
于 2013-02-25T14:29:21.170 回答