使用JQuery/Ajax通过post/get将变量传递到另一个文件,并更改鼠标坐标


Passing variable via post/get to another file using JQuery/Ajax with changing mouse coordinates

我有一个index.php,它会在移动鼠标时监听鼠标坐标。我想把这些坐标发送到第二个文件(比如second.php)。为此,我在鼠标移动活动中放置了post字段。但是我无法在second.php文件中接收这些值。帮我做这件事。我在下面附上我的代码:

<html>
<head>
<script type="text/javascript" src="jquery-latest.js"></script>
<script type="text/javascript">
jQuery(document).ready(function()
{
   $(document).mousemove(function(e)
   {
      $('#status').html(e.pageX);
      $('#status1').html(e.pageY);
        $.post("second.php",
        {
            x:10,
            y:20
        }, function coord(data)
        {   
            $("#div1").load("second.php");  },"html"
        }

   }); 

})
</script>
<body>
<h2 id='status'>
</h2>
<h2 id="status1">
</h2>
<div id="div1"></div>
</body>
</html>

第二个文件通常接收post值,并在添加后返回。我是走错了路,还是有其他方法。帮我吧。

我建议你不要做这件事,每次你移动鼠标时都会发送一个请求,这很难管理——想想其他方法来做你想做的事
但是这个代码可以适用于你的范围:

<script type="text/javascript">
jQuery(document).ready(function()
{
   $(document).mousemove(function(e)
   {
      $('#status').html(e.pageX);
      $('#status1').html(e.pageY);
      $.ajax({
        type: 'POST',
        url: 'second.php',
        data: { 
            'x': '10', 
            'y': '20' 
        },
        success: function(msg){
            //what you want after request
        }
    });
  });
</script>

虽然您可以使用下面的代码发送数据,但由于值的快速更改,这将很难为您进行管理,但我认为最好每隔一段时间从"second.php"读取数据。

$.ajax({
            type: "POST",
            async: true,
            url: 'second.php/Your_function_name',
            data: { 'x': anything , 'y': anything},       
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(r) { 
            alert(r.d); // returned value                         
            }
        });

若您决定从第二个文件中读取数据,请在第一个文件中创建一个返回值数组的方法,然后是

$(document).ready(function() {
GetMousePosition();
}
function GetMousePosition()
{
    $.ajax({
                type: "POST",
                async: true,
                url: 'first.php/GET_MOUSE_VALUES',     
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(r) { 
                MousePositionChanged(r.d[0] , r.d[1]);
                }
            });
     setTimeout(function {GetMousePosition();} , 1000);//Get Values every one second
}

编辑:在第二个解决方案中,您可能会丢失一些值,可以通过创建一个保存最后(可能)5个鼠标位置的数组来轻松管理这些值。最后发送数组。这就是全部