3

我正在使用 Jquery、Ajax 和 PHP 来尝试发送要写入 mysql 数据库的变量。正在发出 Ajax 请求,但 php.ini 未获取该变量。我不知道为什么会这样。

使用 firebug 和 console.log() 我可以看到已经对 write_results.php 进行了 POST

如果我检查它说的响应

注意:未定义的索引:第2E:\write_results.php中的测试分数

这是我的PHP

<?php 
  $testscore=$_POST['testscore'];  //get testscore from Ajax 
  include 'DB.php';
  $con = mysql_connect($host,$user,$pass);
  $dbs = mysql_select_db($databaseName, $con); 
     if (isset($_POST['testscore'])) {  
       $addClient  = "INSERT INTO variables (`id` ,`name`) VALUES (NULL,'$testscore')";  
       mysql_query($addClient) or die(mysql_error());  
       }

?>  

这是我的ajax脚本

<script type="text/javascript">
$(document).ready(function() {  
testscore ="tryagain"; //testvalue to enter into the mysql database
  $.ajax({  
    type: "POST",  
    url: "write_results.php",  
    data: testscore,      
    success: function(){  
      $('#box2').html("success");
    } 
  })
}); 
</script>

我的问题

  1. 为什么 $testscore 没有从 ajax 脚本接收值?
  2. 我怎样才能解决这个问题?
4

3 回答 3

6

你没有告诉 JS 如何发送你的 POST 参数。将您的 JS 更改为:

data: { 'testscore':testscore },

这相当于"testscore=" + testcore形式key=value。它告诉 JS 和 PHP 您希望将变量testscore映射到 key "testscore",然后您将使用它$_POST['testscore']

编辑:参见http://api.jquery.com/jQuery.ajax/,“向服务器发送数据”

于 2011-11-08T05:51:32.827 回答
2

在您的 php 代码中,您可以从 $_POST['testscore'] 中获得 $testscore 值。$_POST 是一个超级全局数组,testscore 是这里的索引。这个 $_POST 数组的索引来自您发布的表单的字段名称。在您的情况下,您使用 ajax 将数据传递到 php 页面。您可以通过 GET 方法或 POST 方法传递。由于您在 ajax 代码中指定 type:POST 时通过 POST 传递,因此您将能够在 php 文件中使用 $_POST 变量。但是您没有在 ajax 代码中指定将保存这些值的数组索引。

testscore ="tryagain"; //It will only assign the value to the javascript variable

您需要提供键值对。你可以用枯萎的方式做到这一点:

testscore="testscore=tryagain"; //In your php code, the testscore will be the array index and tryagain will be its value.

您还可以将键值对以 JSON 格式发送到 PHP 文件,如下所示:

testscore={'testscore':'tryagain'}; 

如果您有多个值(例如两个)要发送,您可以执行以下操作:

testscore={'testscore':'tryagain','index2':'value2'}

如果在 ajax 中使用 post 作为类型,则在您的 PHP 代码中,您可以获得如下信息:

$testscore1=$_POST['testscore']; //It will assign tryagain
$testscore2=$_POST['index2'];    //It will assign value 2
于 2011-11-08T06:27:47.980 回答
0

尝试使用data: "testscore=" + testscore, 数据需要格式化为查询字符串。

于 2011-11-08T05:54:51.043 回答