Magento - Ajax称PHP无法正常工作

时间:2013-04-12 18:45:21

标签: php ajax magento xmlhttprequest

我在local安装了Magento 我在magento\app\design\frontend\base\default\template\catalog\product\view.phtml

中添加了我的Ajax代码

我正在尝试将一些变量发布到与view.phtml相同位置的另一个PHP文件中。

<script>
  function loadXMLDoc()
  {
      var user = "<?php echo $userId;?>";
      var product = "<?php echo $xxx;?>";
      var xmlhttp;
      if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
           xmlhttp=new XMLHttpRequest();
      }
      else
      {// code for IE6, IE5
           xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp.open("POST","test.php",true);
      xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
      xmlhttp.send("userID="+user+"&productID="+product);
      }

      //this is just a countdown timer
     var timeLeft = 3; 
     var timer = window.setInterval(function() {
     timeLeft--;
     var minutesLeft = Math.floor(timeLeft / 60);
     var secondsLeft = timeLeft % 60;
     console.log('Time left: ' + minutesLeft + ':' + secondsLeft);
     if (timeLeft == 0) {
     window.clearInterval(timer);
     // do some ajax thing

     loadXMLDoc();
         }
     }, 1000);
</script>

基本上我会在几秒钟后将2个变量发布到test.php。 我非常确定这些代码是有效的,但是当我在magento产品页面中尝试它们时。 它不起作用。我试图确保,如果所有代码都被执行。 一切运行正常,只有Ajax不会发布在PHP文件中。

在test.php文件中,我只获取2个变量并将其保存到位于同一文件夹中的.txt文件中。 test.php文件仅用于测试目的。

我只需要让Ajax正常工作。我希望它发布到test.php,但保留在同一页面上。

我谷歌周围找到了一些解决方案,它似乎与Magento控制器有某种联系。但我无法理解。

有人可以告诉我是否有一种简单的方法来解决这个问题?


我添加此内容只是为了让事情更清楚。

<?php

  if(isset($_POST['userID']))
  {   
     $userID = $_POST['userID'];
     $productID = $_POST['productID'];

     $file = "db.txt";

     $current = file_get_contents($file);

     $current .= "\n$userID \t $productID";

     file_put_contents($file, $current);
     }

  ?>

并将db.txt放在与test.php

相同的文件夹中

如何知道是否正在调用test.php? 我试着检查db.txt,但内部没有任何改变。


更正

我将test.php和db.txt放在root中。 并改变

xmlhttp.open("POST","test.php",true)

xmlhttp.open("POST","http://localhost/magento/test.php",true)

谢谢你

1 个答案:

答案 0 :(得分:0)

显然,由于view.phtml旁边有test.php,因此xmlhttp.open("POST","test.php",true);会在/test.php上请求POST(这意味着应用程序根目录),因此无效。

请将test.phpdb.txt放在根目录(您可以找到Magento index.php的相同位置)