简体   繁体   English

AJAX将javascript变量发布到php

[英]AJAX to post javascript variable to php

My question is: using AJAX, how do I pass a variable in Javascript to my PHP code? 我的问题是:使用AJAX,如何将Javascript中的变量传递给PHP代码?

I know PHP is server-side and Javascript is client side and I've read at least a dozen questions asking almost or pretty much the same thing but with each one I seem to be missing something because none of them work. 我知道PHP是服务器端的,而Javascript是客户端的,我已经读了至少十二个问题,几乎都问同样的问题,但每个问题我似乎都缺少了一些东西,因为它们都不起作用。 In essence, I am using geolocation to get the user's latitude and longitude on page load and for testing purposes it displays it on the page in respective divs. 实质上,我使用地理位置来获取页面加载时用户的经度和纬度,并且出于测试目的,它在相应的div中将其显示在页面上。 This part works fine. 这部分工作正常。 My issue comes when I try to submit the data to my PHP variables it doesn't connect or something goes wrong, or maybe my code is completely incorrect on this part. 当我尝试将数据提交到我的PHP变量时,它没有连接或出现了问题,或者这部分代码完全不正确,我的问题就来了。

Here is my page for testing in its entirety "test.php": 这是我用于整体测试的页面“ test.php”:

<!DOCTYPE html>
<html>
  <head>
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

   <script>
     x = navigator.geolocation;

     x.getCurrentPosition(success, failure);

     function success(position) {
        var mylat = position.coords.latitude;
        var mylng = position.coords.longitude;
        $('#latit').html(mylat);
        $('#longit').html(mylng);
     }
     function failure() {
        $('#latit').html("<p>It didn't work</p>")
     }

     //sends javascript 'mylat' and 'mylng' from above to php script//
    $.post("test.php", { lat: mylat , lng : mylng});

   </script> 


  </head>
  <body>
    <!--only to validate that geolocation function works-->
    <div id="latit"></div>
    <div id="longit"></div>

    <div id="splash">
        <h2>Click the button</h2>
        <form action="test.php" method="post">


        <input type="submit" name="submit" value="Do the thing!" />
        </form>
    </div>

    <?php
        //used to validate passing of coordinates
    if (isset($_POST['lat'])) {
        echo $lat = $_POST['lat'];
    }
    if (isset($_POST['lng'])) {
        echo $lng = $_POST['lng'];
    }
    ?>
  </body>
</html>

I am attempting to pass the JS 'mylat' and 'mylng' into PHP's $lat and $lng respectively. 我试图将JS'mylat'和'mylng'分别传递到PHP的$ lat和$ lng中。 Any help would be sincerely appreciated and I apologize for the duplicate question, I'm not sure of a better way to frame what I'm asking for. 衷心感谢您的任何帮助,对于这个重复的问题,我深表歉意。我不确定是否有更好的方法来构想我要的内容。

Additionally, if there's a way to do this without having to click anything that would be a bonus but I've found nothing for that. 此外,如果有一种方法可以执行此操作而不必单击任何会带来好处的东西,但我对此一无所获。 I'm very new to web development/programming in general and have almost no experience with Javascript/jQuery/AJAX. 我一般对Web开发/编程都是新手,几乎没有Javascript / jQuery / AJAX的经验。

Firstly, this line: 首先,这一行:

$.post("test.php", { lat: mylat , lng : mylng});

should be in the success function. 应该在成功功能中。 Where it is now it gets executed as soon as the browser parses the <script> tag, however you need to make the POST request when you get the location. 它现在所在的位置在浏览器解析<script>标记后立即执行,但是在获取位置时需要发出POST请求。

And secondly the ajax request you've made won't have effect on the already loaded page, as the results of it will vanish, unless processed. 其次,您发出的ajax请求将不会对已经加载的页面产生影响,因为除非处理,否则其结果将消失。

What you can do is to use $.load() on the body element, this will replace the contents of the current body with the received one: 您可以做的是在body元素上使用$ .load() ,这将用接收到的内容替换当前body的内容:

$(document.body).load("test.php", { lat: mylat , lng : mylng});

Although a better approach would be to have a script that processes the location send via ajax and you render that received content into a custom element from your html page. 尽管更好的方法是让脚本处理通过ajax发送的位置,然后将接收到的内容呈现到html页面的自定义元素中。

Your function named "success" is where you are defining the variables myLat and myLng. 名为“成功”的函数是定义变量myLat和myLng的地方。 When you are making the POST request to the server you are trying to pass the variables' values, but nothing is coming through, right? 当您向服务器发出POST请求时,您试图传递变量的值,但是没有任何结果,对吗? The reason for that is because your post request doesn't have access to the scope of that function. 这样做的原因是因为您的发布请求无权访问该功能的范围。

Try moving the $.post request into the success function, so that it reads like this: 尝试将$ .post请求移到成功函数中,使其内容如下:

function success(position) {
    var mylat = position.coords.latitude;
    var mylng = position.coords.longitude;
    $('#latit').html(mylat);
    $('#longit').html(mylng);
    $.post("test.php", { lat: mylat , lng : mylng});
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM