开发者

XMLHttpRequest to PHP script - what's missing here?

This is my first time using AJAX, and I'm trying to send JS variables to a PHP script. I've got an XMLHttpRequest but it doesn't seem complete - what am I missing?

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
   开发者_如何学Go }
    else {
        document.write("Geolocation is required for this page.");
    }

    function successFunction(position) {
        var lat = position.coords.latitude;
        var lng = position.coords.longitude;
    //    document.write("<a href='http://api.geonames.org/findNearbyPlaceNameJSON?lat="+lat+"&lng="+lng+"&username=sebastiano'>my town</a>");

        var xmlhttp;
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }
        else {
            // code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.open("GET","location.php?lat=position.coords.latitude",true);
        xmlhttp.send();

        // SOMETHING MISSING HERE?

    }

    function errorFunction(position) {
        document.write("Error");
    }


It appears that you're not passing the contents of your variable to the open command.

xmlhttp.open("GET","location.php?lat=position.coords.latitude",true);

in this example your lat will contain a string with contents "position.coords.latitude"

instead try

xmlhttp.open("GET","location.php?lat="+position.coords.latitude,true);

Or better yet, use the variables you created at the top of the function and pass both long and lat in.

xmlhttp.open("GET","location.php?lat=" + lat + "&long=" + lng,true);


you are sending it with "position.coords.latitude" as value...

try xmlhttp.open("GET","location.php?lat=" + position.coords.latitude,true);

Also, take a look at jQuery


Try this:

        var xmlhttp;

        if (window.XMLHttpRequest) {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
        }
        else {
                // code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange=function(){
                if (xmlhttp.readyState==4 && xmlhttp.status==200){
                        console.log(xmlhttp.responseText);
                }
        }

        xmlhttp.open("GET","location.php?lat=" + position.coords.latitude,true);
        xmlhttp.send();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜