【问题标题】:Ajax Post Value not being passed to php fileAjax Post 值未传递到 php 文件
【发布时间】:2014-03-06 13:40:03
【问题描述】:

我在将变量传递到 php 页面时遇到问题。

下面是代码:

var varFirst = 'something'; //string
var varSecond = 'somethingelse'; //string

$.ajax({  
   type: "POST",  
   url: "test.php",  
   data: "first="+ varFirst +"&second="+ varSecond,  
       success: function(){  
          alert('seccesss');

   }
});

PHP:

$first = $_GET['first']; //This is not being passed here
$second = $_GET['second']; //This is not being passed here

$con=mysqli_connect("localhost","root","pass","mydb"); 

if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_query($con,"INSERT INTO mytable (id, first, second) VALUES ('', $first, $second)");

mysqli_close($con);


}

我错过了什么?实际数据正在保存到数据库中,但 $first 和 $second 值没有传递到 php 文件。

【问题讨论】:

  • 您应该将数据作为 JSON 传递。

标签: javascript php


【解决方案1】:

您正在使用 POST 类型,在 POST 中检索它:

$first = $_POST['first'];
$second = $_POST['second'];

或者改变你的 JQuery 调用:

$.ajax({  
   type: "GET",  
   url: "test.php",  
   data: "first="+ varFirst +"&second="+ varSecond,  
       success: function(){  
          alert('seccesss');
   }
});

【讨论】:

    【解决方案2】:

    这是因为您正在传递数据 throw POST 方法并尝试使用 GET 获取所以更改这两行

    $first = $_POST['first']; //This is not being passed here
    $second = $_POST['second']; //This is not being passed here
    

    或者只是在 jquery 中将方法更改为 GET

    type: "GET"
    

    【讨论】:

      【解决方案3】:

      您在 ajax 中使用 type: "POST" 并尝试使用 $_GET 获取,尝试

      $first = $_REQUEST['first']; //This is not being passed here
      $second = $_REQUEST['second'];
      

      【讨论】:

        【解决方案4】:

        还有一种方法可以传递这样的数据

        $.ajax({  
           type: "POST",  
           url: "test.php",  
           data: {first: varFirst,second: varSecond},  
               success: function(){  
                  alert('seccesss');
        
           }
        });
        

        你可以在那里使用

        $_POST['first'];
        $_POST['second'];
        

        希望对你有帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-08-07
          • 1970-01-01
          • 2022-06-10
          • 2015-05-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多