Ajax问题:未定义索引,我应该怎么做?

时间:2019-06-06 12:50:45

标签: php ajax

我正在尝试为一个新项目学习ajax,我需要使用一些javascripts变量上载数据,因此为了开始,我决定尝试一个简单的ajax小问题,但是我没有用,

  

注意:未定义索引:显示第4行C:\ Apache24 \ htdocs \ d.php中的名称

我的.js文件:

<script>

$.ajax({
    type: "POST",
    url: 'd.php',
    data: {name : "aa"},
    success: function(output) {
        alert(output);
    }
    error: function(request, status, error){
            alert("Error: Could not delete");
    }
);
        </script>

我的php文件:

<?php

print_r($_POST['name']);

?>

谢谢

4 个答案:

答案 0 :(得分:0)

好吧,我在项目中编写了代码,以了解问题所在,确实代码正确,但是您缺少“,”和“}” 您可以在下面看到工作代码:

    $.ajax({
        type: "POST",
        url: 'd.php',
        data: {name : "aa"},
        success: function(output) {
            alert(output);
        },
        error: function(request, status, error){
            alert("Error: Could not delete");
        }
    });

另一个提示,在.php文件中添加一个检查:

if(isset($_POST)){
   my_data = $_POST['name'];
}

做得很好!

答案 1 :(得分:-2)

Forbid

对我来说PHP:

3 mistakes:
1 - name : aa
2 - comma after success function
3 - } at the end of ajax

var aa = 1234;

$.ajax({
    type: "POST",
    url: 'd.php',
    data: {name : aa},
    success: function(output) {
        alert(output);
    },
    error: function(request, status, error){
            alert("Error: Could not delete");
    }
           });

答案 2 :(得分:-4)

在javascript中尝试此代码。

$.ajax({
    enter code here
    url: 'd.php',
    data: {name : "aa"},
    type: 'post',
    dataType: 'json',
}).then(function(output) {
    alert(output);
}, function(request, status, error){
    alert("Error: Could not delete");
});

答案 3 :(得分:-8)

它不是那样工作的,您永远也看不到幕后发生的事情,唯一的出路是将请求记录到txt文件中。

仅当ajax发送POST请求时才定义您的变量,要查看它是否成功,请像下面这样编辑代码:

<?php
  //if post is set
  if(isset($_POST['name'])) {
     //open log.txt
      $file = fopen('log.txt', 'a'); 
     //ensure print_r give a return
       fwrite($file, print_r($_POST, true);
     //close log.txt
       fclose($file); 
   }
?>

确保您创建文件log.txt

完成此操作后,发送ajax请求并在log.txt中查看$ _POST变量