How can I pass saved localStorage web data to a php script?

前端 未结 2 1401
名媛妹妹
名媛妹妹 2021-01-15 03:10

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

相关标签:
2条回答
  • 2021-01-15 03:49

    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"];
    
    0 讨论(0)
  • 2021-01-15 04:02

    You have code error

    It should be oReq.onload = reqListener; oReq.open("get", "snap.php? lat="+localStorage.latitude+"&lon="+localStorage. lon, true); oReq.send();

    0 讨论(0)
提交回复
热议问题