普通网友 2013-02-25 14:06
浏览 52

Json Ajax PHP为NULL

I get an array with the geolocation JavaScript, then I want to pass this array to a php script via ajax to process it and get an processed array back. Unfortunately it seems that the passed array to php is always NULL, I have no idea why.

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

My php:

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

The result is always ["jsonArray"]=> NULL.

  • 写回答

2条回答 默认 最新

  • weixin_33721344 2013-02-25 14:25
    关注

    try this one. it works for me

     (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();
        */
    }
    
    
    
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog