Post请求中的未定义索引

时间:2014-06-23 06:53:05

标签: php jquery ajax undefined-index

我不知道为什么我会收到这个奇怪的错误!

  

PHP注意:未定义的索引:第5行/var/www/echo.php中的refId

我正在获取控制台输出,但无法回显refId。我在这做错了吗?

<?php
    $rollUrl = 34;
    $refId = $_POST['refId'];
    echo $refId;
?>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
    $.ajax({
        url:'echo.php',
        type: 'POST',
        data: { 'refId': "<?php echo $rollUrl ?>" },
        success: function(response){
            console.log('Getting response');
        }
    }); 
</script>

2 个答案:

答案 0 :(得分:1)

请参阅以下代码中的评论:

<?php
$rollUrl = 34;

//Only try to process POST if there is something posted *and* refId exists
if (count($_POST) > 0 && isset($_POST['refId'])) { 
  $refId = $_POST['refId'];
  echo $refId;
  //Exit after echoing out the refId so that the HTML below does not also get returned.
  exit();
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
    $.ajax({
        url:'echo.php',
        type: 'POST',
        data: { 'refId': "<?php echo $rollUrl ?>" },
        success: function(response) {
            //Updated log to show the actual response received.
            console.log('Getting response of "' + response + '"');
        }
    }); 
</script>

当我测试时没有任何错误被抛出并且正在执行Ajax时,这对我有用。

答案 1 :(得分:0)

这种情况正在发生,因为您的变量未设置。使用isset

<?php

$rollUrl=34;
if(isset($_POST['refId'])) {
$refId=$_POST['refId'];
echo $refId;
}

?>

<强>更新: 您应该将refId作为名称属性分配给任何输入字段,以恢复用户的输入。

<input type="text" name="refId" />