问题描述
我正在编写一个模块来在 Magento 中执行一个简单的 Ajax 调用,但到目前为止我无法让它工作 - 我觉得我在某处缺少一个重要的组件.这些是我目前拥有的文件:
I'm writing a module to carry out a simple Ajax call in Magento, but I'm unable to get it work thus far - I feel like I'm missing a vital component somewhere. These are the files I currently have:
Creare/Groupedajax/controllers/AjaxController.php:
class Creare_Groupedajax_AjaxController extends Mage_Core_Controller_Front_Action { public function indexAction() { $this->loadLayout(); $this->renderLayout(); } }
Creare/Groupedajax/etc/config.xml:
<?xml version="1.0"?> <config> <modules> <Creare_Groupedajax> <version>0.1.0</version> </Creare_Groupedajax> </modules> <frontend> <routers> <groupedajax> <use>standard</use> <args> <module>Creare_Groupedajax</module> <frontName>groupedajax</frontName> </args> </groupedajax> </routers> <layout> <updates> <groupedajax> <file>groupedajax.xml</file> </groupedajax> </updates> </layout> </frontend> </config>
我的 Ajax 调用:
$j.post("groupedajax/ajax/index", { size: $j(this).val()}, function(data) { $j('#results').html(data); });
layout/groupedajax.xml:
<?xml version="1.0"?> <layout version="1.0"> <groupedajax_ajax_index> <block type="groupedajax/groupedajax" name="root" output="toHtml" template="groupedajax/groupedajax.phtml" /> </groupedajax_ajax_index> </layout>
我的 .phtml 文件目前只有测试".我只需要我的结果 div 返回测试"值.我只是想知道是否所有的位都到位以使其正常工作?
My .phtml file simply has 'test' in it at the moment. I just need my results div to return the 'test' value. I just want to know if all the bits are in place for this to work?
这是我遵循的教程:http://www.atwix.com/magento/ajax-requests-in-magento/
======================== 已解决 ==========================
我只需要在我的网址开头加一个正斜杠:
I just needed a forward slash at the beginning of my url:
$j.ajax({ url: "/groupedajax/ajax/index", type: "POST", data: "size="+$j(this).val(), success: function(data) { $j('#results').html(data); } });
推荐答案
如果您的 javascript 是从 .phtml 模板文件输出的,那么您可以使用 一个方便的函数,使 URL 完全合格,这将是最安全的处理方式.
If your javascript is being output from a .phtml template file then you can use a convenience function to make the URL fully-qualified which will then be the safest way to proceed.
$j.ajax({ url: "<?php echo $this->getUrl('groupedajax/ajax/index') ?>", type: "POST", data: "size="+$j(this).val(), success: function(data) { $j('#results').html(data); } });