3

我有 index.php 它将在移动它时监听鼠标坐标。我想将这些坐标发送到第二个文件(比如 second.php)。为此,我在鼠标移动活动中放置了帖子字段。但我无法在 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 值并在添加后返回。我是走错了路还是有另一种方法可以做到这一点。帮我解决。

4

2 回答 2

2

我建议您不要这样做,每次移动鼠标时发送请求都很难管理,请考虑另一种方式来做您想做的事。
但此代码适用于您的范围:

<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>
于 2013-07-27T09:35:44.420 回答
0

尽管您可以使用下面的代码发送数据,但由于快速更改值,您将很难管理,但我认为在某些时间间隔从“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 个鼠标位置的数组来轻松管理这些值。最后发送数组。就这样

于 2013-07-27T09:47:23.570 回答