【问题标题】:Undefined index on ajax post requestajax post请求上的未定义索引
【发布时间】:2016-07-19 10:06:00
【问题描述】:

这似乎是一个重复的问题,但事实并非如此。我已经搜索了谷歌,但我的错误仍然存​​在。

问题在于 php 脚本无法将 $_POST 数组设置为 ajax 发布请求传递的值。我有一个表单,提交时会在与第一个表单相同的 div 中显示另一个表单。第二个表单包含一个提交按钮,以及一个发送 ajax 发布请求的按钮,但它的值不是由 php 设置的。代码如下:

html代码:就是选择span的值。

<i>Current Balance: <span id="bal_val"><?php echo $b; ?></span></i>
<div id="bal" style='color:green;'>

Ajax 代码: 这里,编辑按钮是一个按钮(第一种形式的),它可以显示第二种形式。第二种形式包含 balbutton 输入,它发送 ajax 请求。

 $('#edit').click(function(event){  
          event.preventDefault();
$('#bal').html('<button class="btn1 btn-1 btn-1b" id="balbutton" name="balbutton">Add 1000 Rs.</button>');
});

$('#balbutton').click(function(event){
              event.preventDefault();

              var bal = document.getElementById('bal_val').innerHTML;
              var balance = parseInt(bal);
             var dataString = {balance};

               $.ajax({
                                    type: "POST",
                                    url: "admin.php/",
                                    data: dataString,
                                    contentType: 'application/x-www-form-urlencoded',
                                    cache: false,
                                    dataType: 'text',
                                    success: function(result){
                                    var data="";
                                    console.log(result);
                                    $('#bal').html('We will add 1000rs to your account soon');
                                    },
                                    error: function(error){console.log(error);}
                            });  

      });

php代码:

<?php 

$bal=$_POST['balance'];

$bal=intval($bal);
echo $bal;

echo '<pre>';
echo print_r($_POST);
echo '</pre><br>';

echo '<pre>';
echo var_dump($_POST);
echo '</pre>';
?>

另外,我尝试了以下解决方案:

  1. Undefined index: Error in ajax POST and/or php script?
    1. jquery ajax => Undefined index php
    2. Undefined index in PHP post with AJAX
    3. Undefined index error in php using ajax
    4. http://forums.devshed.com/php-development-5/jquery-json-php-undefined-index-950332.html

ajax post 请求和 PHP 错误的快照

【问题讨论】:

  • var dataString = {balance}; 应该是var dataString = {balance:balance};
  • @ThinkDifferent, {balance}ES2015 的正确语法
  • @vp_arth ES2015/ES6 在 Firefox 中尚未原生支持。

标签: javascript php jquery html ajax


【解决方案1】:

在这部分,你没有给出有效的语法:

var dataString = {balance};

将以上内容改为:

var dataString = {balance: balance};

【讨论】:

  • 是的,我试过了。它没有用。我还提到了一个提到相同解决方案的链接。不管怎么说,还是要谢谢你! :)
  • @simrandhamija 您能否尝试对 Chrome 执行相同的操作,并检查“网络”选项卡,这是怎么回事?截图会很棒。
  • 我添加了快照!不幸的是它在Firefox上,希望你不介意。我还强调了相关的帖子请求。
  • @simrandhamija 谢谢。您还可以在其中包含 form data 部分吗?对不起,这是我要落后的主要事情......
  • @simrandhamija 你真的需要这条线吗? contentType: 'application/x-www-form-urlencoded',
猜你喜欢
  • 2014-08-13
  • 1970-01-01
  • 2019-08-18
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 2016-05-18
  • 2014-12-19
  • 2019-07-04
相关资源
最近更新 更多