【问题标题】:Undefined index error when sending variable from jquery to php将变量从 jquery 发送到 php 时出现未定义的索引错误
【发布时间】:2015-07-05 09:09:39
【问题描述】:

改编自这个问题:Passing Jquery variable to php within a modal

我已经设置好了,它应该可以工作,但是我得到了未定义的索引错误。

在while循环内:

print '<li>';
        print '<a class="btn btn-default" data-toggle="modal" data-id='.$row['id'].' data-target=".bs-example-modal-lg"><img src="'.$row["image"].'" /></a><br>';
        print '<a class="btn btn-default" data-toggle="modal" data-id='.$row['id'].' data-target=".bs-example-modal-lg"><h4>'.$row['name'].'</h4></a>';
print '</li>';

我所有的 jquery,包括 ajax 代码:

 $(document).ready(function() {
            $("body").css("display", "none");
            $("body").fadeIn(1000);
            $("a.transition").click(function(event){
                event.preventDefault();
                linkLocation = this.href;
                $("body").fadeOut(1000, redirectPage);      
            });
            function redirectPage() {
                window.location = linkLocation;
            }
        }); 
$(document).on("click", ".btn", function (e) {
            e.preventDefault();
            alert (id);
            var id = $(this).data('id');
            alert (id);
            $("h4.modal-title").text(id);

            //$($(this).attr('href')).modal('show');    
            $.post('food.php',{id:id},function(data){
                alert(data);
                alert (id) // <--THIS ALERT WORKS TOO
            });
        });

php:

<?php
        $id = $_POST["id"];
        print '<h4>'.$id.'</h4>'

    ?>

我在$id = $_POST["id"]; 上不断收到索引未定义错误。

我似乎不明白为什么,我已经将我的代码调整为许多不同的方法,但它们都不起作用。

第一个警报出现,但第二个没有。文本确实放置在&lt;div&gt; 中,但它不会发送到变量。所有这些都在一个文件中。 我感觉我的 ajax 代码缺少一些东西。

Var 转储显示:

array (size=0)
   empty

【问题讨论】:

  • 我没有在你的 a 标签中看到 href 属性。
  • 啊,我可以把这段代码注释掉,它仍然给出错误
  • 奇怪,你能不能把var id = $(this).data('id');换成var id = $(this).attr('data-id');。
  • @Devon 您必须为 obj[id] = id 使用方括号表示法,否则是的,它不会考虑变量的值。
  • 如果您尝试将数据发送为{id: 'test'} 只是为了测试一下呢?并检查网络选项卡中正在发送的参数。

标签: php jquery html ajax twitter-bootstrap


【解决方案1】:

使用下面的php代码再试一次

<?php
    if( isset( $_POST["id"] ) ) 
        $id = $_POST["id"];
    else
        $id = 'Error: id not exist';
    print '<h4>'.$id.'</h4>';
    die();
?>

【讨论】:

  • 显示错误:id 不存在
  • 我没有得到你的代码:var id = $(this).data('id');你想从这段代码中得到什么?
  • 所以当有人点击图片或者名字的时候,id被转移到jquery变量id中。 (认为​​这就是它的意思)
【解决方案2】:

您已经假设数据已发布。 如果 isset 试试

if(isset($_POST['id']))
{
     $id = $_POST["id"];
  echo $id;
    }

【讨论】:

  • 这也不返回任何东西
  • 它不返回任何东西,因为没有数据被传递。检查这行代码 var id = $(this).data('id');而是尝试添加 var id = $(this).data('data-id');
  • 也没有区别
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-25
  • 2014-09-16
  • 2015-08-07
  • 2019-04-03
相关资源
最近更新 更多