我正在尝试替换“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/