如何修复此未定义的索引错误?Jquery Ajax到PHP

Try*_*der 3 php jquery post undefined-index

我正在使用Jquery,Ajax和PHP来尝试发送一个要在mysql数据库中编写的变量.正在进行Ajax请求,但php没有获取变量.我不知道为什么会这样.

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

如果我检查响应它说

注意:未定义的索引:第2行的E:\ write_results.php中的testscore

这是我的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());  
       }

?>  
Run Code Online (Sandbox Code Playgroud)

这是我的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>
Run Code Online (Sandbox Code Playgroud)

我的问题

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

nic*_*ckb 6

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

data: { 'testscore':testscore },
Run Code Online (Sandbox Code Playgroud)

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

编辑:请参阅http://api.jquery.com/jQuery.ajax/,"将数据发送到服务器"