【问题标题】:Passing PHP variable to another PHP file with AJAX使用 AJAX 将 PHP 变量传递给另一个 PHP 文件
【发布时间】:2013-07-16 18:16:02
【问题描述】:

我的问题是:我必须使用 ajax 调用将变量从 a.php 传递给 b.php,该调用从 a.php 获取变量 'numitems' 并将其传递给 b.php...

我的代码在下面,但是当我尝试在 b.php 中检索“numitems”时,我收到了这条消息:

注意:未定义的索引:第 19 行 b.php 中的 numitems

    stringaPost();        
    xmlHttp.open('POST', "b.php", true);    
    xmlHttp.onreadystatechange = function() {
        if(xmlHttp.readyState == 4) { 
            if (xmlHttp.status == 200) { 
            data: {numitems : <?php $numitems;?> }
            document.getElementById("primaryContent").innerHTML=xmlHttp.responseText;
            }
        }
    }; 

在 b.php 中我有:

$numitems = $_POST['numitems'];

问题大概出在数据上:{numitems : &lt;?php $numitems;?&gt; 但我不确定,也无法找出问题的根源。

【问题讨论】:

标签: php ajax


【解决方案1】:

您需要在请求中设置数据而不是成功回调。正如其他几个人指出的那样,您的 php 中也缺少 echo 语句。

stringaPost();     
xmlHttp.open('POST', "b.php", true);    
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = function() {
    if(xmlHttp.readyState == 4) { 
        if (xmlHttp.status == 200) { 
            document.getElementById("primaryContent").innerHTML=xmlHttp.responseText;
        }
    }
}; 
xmlHttp.send("numitems=<?php echo $numitems;?>");

【讨论】:

  • 谢谢,最后一行是我错过的。
  • 我还要问你一件事。我们在 b.php 和 $numitems 其中 $_POST['numitems'] 应该增加 1。所以我们做 $numitems++ 并且在我将它返回给 a.php 之后,我该怎么做?再次感谢
  • 在 b.php 中,您需要将新的numitems 打印到您的onreadystatechange 函数中通过xmlHttp.responseText 获取的页面。如果您需要同时发回新号码和其他内容,则需要通过将它们打印到页面来将它们发回,然后在 onreadystatechange 函数中使用 javascript 解析返回的页面。
猜你喜欢
  • 1970-01-01
  • 2019-02-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-23
  • 2011-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多