【问题标题】:How can I fix this undefined index error? Jquery Ajax to PHP如何解决这个未定义的索引错误? Jquery Ajax 到 PHP
【发布时间】:2011-12-24 04:37:46
【问题描述】:

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

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

如果我检查它说的响应

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

这是我的 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. 我该如何解决这个问题?

【问题讨论】:

    标签: php jquery post undefined-index


    【解决方案1】:

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

    data: { 'testscore':testscore },
    

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

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

    【讨论】:

    • 我刚刚意识到发送到 php 的信息是“tryagain”,所以你的回答很有意义。非常感谢您的回答!!!
    【解决方案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
    

    【讨论】:

    • 感谢非常详细的回答!这很容易理解。
    【解决方案3】:

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

    【讨论】:

    • 不一定 - 数据可以接受查询字符串或值映射。
    • 感谢卢克的快速回复 :)
    猜你喜欢
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 2014-10-07
    • 2016-04-21
    • 2017-02-25
    相关资源
    最近更新 更多