我如何将保存的localStorage Web数据传递给PHP脚本? [英] How can I pass saved localStorage web data to a php script?

查看:87
本文介绍了我如何将保存的localStorage Web数据传递给PHP脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我在尝试查找如何将一些已保存在localStorage中的数据传递给我编写的php脚本时遇到了一些问题,所以我可以将它们发送到服务器上的数据库。我以前找过一些代码,( https://developer.mozilla.org / en-US / docs / DOM / XMLHttpRequest / Using_XMLHttpRequest ),看起来像它会工作,但我没有运气。



这里是我保存数据的代码,并且试图通过我的phpscript来传递它

  function getLocation(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(initialize,showError,takeSnap);
}
else {
alert(此浏览器不支持地理定位。);



函数初始化位置{
var lat = position.coords.latitude,
lon = position.coords.longitude;

var mapOptions = {
center:new google.maps.LatLng(lat,lon),
zoom:14,
mapTypeId:google.maps.MapTypeId。 ROADMAP,
mapTypeControl:true
}

var map = new google.maps.Map(document.getElementById(map-canvas),mapOptions);
var marker = new google.maps.Marker({
position:new google.maps.LatLng(lat,lon),
map:map,
title:当前位置
});


函数showError(错误){
switch(error.code){
case error.PERMISSION_DENIED:
alert(用户拒绝了请求地理定位。);
休息;
case error.POSITION_UNAVAILABLE:
alert(位置信息不可用。);
休息;
case error.TIMEOUT:
alert(请求获取用户位置超时。);
休息;
case error.UNKNOWN_ERROR:
alert(发生未知错误。);
休息;



函数storeLocal(位置){
if(typeof(Storage)!==undefined){
var lat = position .coords.latitude,
lon = position.coords.longitude;

localStorage.latitude = lat;
localStorage.longitude = lon;
}
else {
alert(您的浏览器不支持网络存储);
}
$ b $ return
}

function snapShot(){
if(navigator.geolocation){
navigator.geolocation .getCurrentPosition(storeLocal,showError);
}
else {
alert(此浏览器不支持地理定位。);
}

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open(post,snap.php?lat =+ localStorage.latitude +& lon =+ localStorage.longitude,true);
oReq.send();
}

函数reqListener(){
console.log(this.reponseText);



$ b $ p
$ b

这是他们写的将值保存到数据库中的脚本

 <?php 
//连接到数据库
mysql_connect(localhost,username,password );
mysql_select_db(db_name);

$ latitude = mysql_real_escape_string($ _ GET [lat]);
$ longitude = mysql_real_escape_string($ _ GET [lon]);

//提交查询插入新数据
$ sql =INSERT INTO locationsTbl(locID,lat,lon)VALUES('NULL','。$ latitude。',' 。$ longitude。');
$ result = mysql_query($ sql);

//通知用户
echo< script> alert('Location saved。');< / script>;

//关闭连接
mysql_close();
?>


解决方案

如何



  oReq.open(get,snap.php?lat =+ localStorage.latitude +& lon =?+ localStorage.longitude,true ); 

(您也有 localStorage.lon .longitude



由于值(字符串)在变量中,因此您需要连接它们,他们在字符串中。



另外,由于您似乎将这些内容传递给您的PHP以保存到数据库,因此从语义上讲,您应该使用POST请求。 ..它的处理方式与AJAX请求不同。



在您的PHP中,您需要使用:

  $ latitude = $ _GET [lat]; 
$ longitude = $ _GET [lon];

来实际获取GET请求发送的值。虽然这些值应该避开SQL注入。



另外,我不确定为什么要设置 onload AJAX请求的属性。相反,使用 onreadystatechange 属性...就像:

  oReq如果(oReq.status> 199&&o; oReq.status< 400){
console.log(成功响应);
} else {
console.log(failed response:+ oReq.status);
}
}
};

.readyState 属性是指其状态,其中 4 表示完成(响应已经回来)。 .status 属性指向HTTP状态码。通常在 200 & 400 很好。我知道我只见过 的人检查 200 (不是范围)。

<为了在请求中传递POST参数,你不要将它们追加到URL中 - 你将它们传递给它们:

UPDATE

.send()方法。以下是您的代码示例:

  oReq.open(POST,snap.php,true); 
oReq.setRequestHeader(Content-type,application / x-www-form-urlencoded);
oReq.send(lat =+ encodeURIComponent(localStorage.latitude)+& lon =+ encodeURIComponent(localStorage.longitude));

要在PHP中检索它们,您可以使用:

  $ latitude = $ _POST [lat]; 
$ longitude = $ _POST [lon];


Alright, so I'm having some issues on trying to find out how to pass some data that i have saved in localStorage over to a php script that I wrote, so I can then send that over to my database on a server. I did find some code earlier, (https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest), that looked like it would work but I had no luck with it.

Here's the code where I am saving the data and than trying to pass it over my phpscript

function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(initialize, showError, takeSnap);
        }
        else {
            alert("Geolocation is not supported by this browser.");
        }
    }

function initialize(position) {
        var lat = position.coords.latitude,
            lon = position.coords.longitude;

        var mapOptions = {
            center: new google.maps.LatLng(lat, lon),
            zoom: 14,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: true
        }

        var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(lat, lon),
            map: map,
            title: "Current Location"
        });
    }

function showError(error) {
        switch (error.code) {
            case error.PERMISSION_DENIED:
                alert("User denied the request for Geolocation.");
                break;
            case error.POSITION_UNAVAILABLE:
                alert("Location information is unavailable.");
                break;
            case error.TIMEOUT:
                alert("The request to get user location timed out.");
                break;
            case error.UNKNOWN_ERROR:
                alert("An unkown error occurred.");
                break;
        }
    }

function storeLocal(position) {
        if (typeof (Storage) !== "undefined") {
            var lat = position.coords.latitude,
                lon = position.coords.longitude;

            localStorage.latitude = lat;
            localStorage.longitude = lon;
        }
        else {
            alert("Your Browser doesn't support web storage");
        }

        return
    }

    function snapShot() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(storeLocal, showError);
        }
        else {
            alert("Geolocation is not supported by this browser.");
        }

        var oReq = new XMLHttpRequest();
        oReq.onload = reqListener;
        oReq.open("post", "snap.php?lat=" + localStorage.latitude + "&lon=" + localStorage.longitude, true);
        oReq.send();            
    }

    function reqListener() {
        console.log(this.reponseText);
    }

This is they script I wrote to save values into database

    <?php
    // Connecting to the database
    mysql_connect("localhost", "username", "password");
    mysql_select_db("db_name");

    $latitude = mysql_real_escape_string($_GET["lat"]);
    $longitude = mysql_real_escape_string($_GET["lon"]);

    // Submit query to insert new data
    $sql = "INSERT INTO locationsTbl(locID, lat, lon ) VALUES( 'NULL', '". $latitude ."', '". $longitude . "')";
    $result = mysql_query( $sql );

    // Inform user
    echo "<script>alert('Location saved.');</script>";

    // Close connection
    mysql_close();
    ?>

解决方案

How about:

oReq.open("get", "snap.php?lat=" + localStorage.latitude + "&lon=?" + localStorage.longitude, true);

(you also had localStorage.lon instead of .longitude)

Since the values (strings) are in variables, you need to concatenate them, not put them in the string.

Also, since you seem to be passing these things to your PHP to save to the database, semantically speaking, you should be using a POST request...which is handled differently with AJAX requests.

In your PHP, you need to use:

$latitude = $_GET["lat"];
$longitude = $_GET["lon"];

to actually get the values that were sent with the GET request. Although these values should be escaped to avoid SQL injection.

Also, I'm not sure why you're setting the onload property of the AJAX request. Instead, use the onreadystatechange property...something like:

oReq.onreadystatechange = function () {
    if (oReq.readyState === 4) {
        if (oReq.status > 199 && oReq.status < 400) {
            console.log("successful response");
        } else {
            console.log("failed response: " + oReq.status);
        }
    }
};

The .readyState property refers to its state, where 4 means it's done (response has come back). The .status property refers to the HTTP status code. Normally between 200 & 400 is good. I know I've seen people only check for 200 (not a range).

UPDATE:

In order to pass POST parameters in the request, you don't append them to the URL - you pass them in the .send() method. Here's an example with your code:

oReq.open("POST", "snap.php", true);
oReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
oReq.send("lat=" + encodeURIComponent(localStorage.latitude) + "&lon=" + encodeURIComponent(localStorage.longitude));

And to retrieve them in PHP, you'd use:

$latitude = $_POST["lat"];
$longitude = $_POST["lon"];

这篇关于我如何将保存的localStorage Web数据传递给PHP脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆