php - 无法读取 null 的属性 'replaceWith' - ajax 调用

标签 php jquery ajax magento replacewith

我正在尝试替换“Hello world!”使用 ajax 替换“你好”。但是我收到此错误:

Cannot read property 'replaceWith' of null

我哪里走错路了?

注意:ajax 调用与alert(response) 配合使用;

index.phtml:

<div id="helloworld">Hello world!</div>

<script type="text/javascript">
    jQuery.ajax({
        url: "<?php echo $this->getUrl('topperproductqa/index/ajax') ?>",
        success: function(response){
            $('#helloworld').replaceWith(response);
            //alert(response);
        }
    });
</script>

IndexController.php:

class Topper_ProductQA_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
        $this->loadLayout();
        $this->renderLayout();

        return $this;
    }

    public function ajaxAction ()
    {
        $response = "Hello to you too";

        $json =  json_encode($response);
        $this->getResponse()->setHeader('Content-type', 'application/json');
        $this->getResponse()->setBody($json);
    }
}

最佳答案

我发现Magento在prototype.js上使用了$,我用以下方法修复了它:

(function($) {

    $.ajax({
        url: "<?php echo $this->getUrl('topperproductqa/index/ajax') ?>",
        dataType: "json",
        success: function(response){
            $("#helloworld").replaceWith(response);
            //alert(response);
        }
    });

})(jQuery);

关于php - 无法读取 null 的属性 'replaceWith' - ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41738191/

相关文章:

Play Framework 1.3.x 中的 PHP 查询

javascript - 检查子对象是否存在,如果存在,则添加到对象

javascript - 选择单选按钮时隐藏特定的表单输入

javascript - 具有不同输入速度的嵌套 AJAX

php - 在 Laravel Ajax 请求验证中获取错误字段名称

php - 在PHP环境中将Docker与Xdebug和Sublime Text集成

javascript - 从 wordpress 站点中删除脚本

php - 元素临 : Change or remove category/tag/author prefix from Archive Title

javascript - 如何使用jquery在表单提交之前显示通知?

javascript - 如何让jquery停止执行1秒