dtcuv8044 2013-05-07 14:23
浏览 121

jQuery $ .post()执行两次之后的php代码

I am still new to PHP and AJAX but I think I have some grasp about JavaScript and jQuery. Here is my problem: In my UI I have a form input field and an OK-button (which is not part of the form). Everytime the user clicks the ok-button, the content of the input field plus some session variables shall be sent to the server via AJAX, so that the page does not have to reload.

Here is my js-Code:

$.post('api/someFile.php',
  {
    var1: nr1,
    var2: nr3,
    var3: nr3,
  }
);

Here is my php-Code someFile.php:

<?php
  // activate current session
  session_start();

  // use php console for debugging    
  require_once('PhpConsole.php');
  PhpConsole::start();

  // get data from UI
  $var1 = $_POST["var1"];
  $var2 = $_POST["var2"];
  $var3 = $_POST["var3"];

  debug("start receiving");
  debug($var1 . " " . $var2 . " " . $var3);

  // ... proceed with the data and write it in database...

  debug("finished");
?>

The problem is that all the code in someFile.php is executed twice. This is the console output:

javascript debug: send to server: nr1, nr2, nr3
php debug: start receiving
php debug: nr1 nr2 nr3
php debug: finished
php debug: start receiving
php debug: nr1 nr2 nr3
php debug: finished

However, the data gets written in the database only once. That is quite weird. Is that a bug in the php console or is my code bad?

  • 写回答

1条回答 默认 最新

  • duanjiaoxi4928 2017-11-27 06:32
    关注

    its happening because HTTP OPTIONS executed first, and you have you restrict unwanted HTTP method before executing your Logic, always use isset method,see example below

    if(isset($_POST))
     {
        $name = $_POST["name"];
        $country = $_POST["country"];
    
        $sql = 'INSERT INTO user values("' . $name . '","' . $country . '")';
    
                if ( $conn->query($sql)=== TRUE) 
                {
                    $outp =  "Inserted " .  $name . "  and  "  . $country;
                    echo json_encode($outp);
                } else {
                    echo json_encode("Error: " . $sql . "<br>" . $conn->error);
                }
            }
    

    here it will insert row in table only when its POST METHOD.

    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法