从javascript传递id到php脚本

Passing id to php script from javascript

本文关键字:php 脚本 id javascript 传递      更新时间:2023-09-26

我有javascript代码传递id到我的php脚本的时间间隔,一旦id不被传递(it means the user has closed the javascript page)。if语句中的块应该在php脚本中运行。但这种情况不会发生在我身上。

代码在

下面JavaScript

<script type="text/javascript" src="jquery-1.11.1.js"></script>
<script type="text/javascript" >
$(function(){
    // set interval for 5 second
    setInterval(function(){
            $.ajax({url: "test9.php?id=('1')"
            });
    }, 50000);
});
</script>
PHP

<?php
while(true)
{
    $id = $_GET['id'];
    if(isset($_GET['id']))
    {
        file_put_contents('/tmp/phptest1234.txt', 'test');
    }
    else
    {
        file_put_contents('/tmp/phptest.txt', 'test');
    }
}
?>

如果页面被关闭,那么页面将不会向服务器发送任何AJAX请求。这样情况就不会出现。所以它只在if中,else部分不会在任何时候被执行。

如果你想,get请求将在页面关闭时被调用,那么你可以尝试以下操作:-

<body onbeforeunload="closePage()">
</body>

然后在closePage函数中使ajax请求没有id:-

<script type="text/javascript" >
$(function(){
// set interval for 5 second
setInterval(function(){
        $.ajax({url: "test9.php?id=('1')"
        });
}, 50000);
});
function closePage(){
 $.ajax({url: "test9.php
 });
}
</script>

url不应该有('1'),您需要更改以下行

$.ajax({url: "test9.php?id=('1')"

$.ajax({url: "test9.php?id=1"

您可以通过AJAX数据属性传递id,如下所示。

get request

    $.ajax({
        type:'get',
        url:'test9.php',
        data:{'val':value},
        success:function(data){
              }

by post request

    $.ajax({
        type:'get',
        url:'test9.php',
        data:{'val':value},
        success:function(data){
              }