Quantcast
Channel: Magento – Marcel Schmidt Wiki / Neuigkeiten
Viewing all articles
Browse latest Browse all 10

Magento Controller Ajax and json Response and Request Prototype

$
0
0

Folgend möchte ich zeigen wie man per Prototype einen Controller abruft, wie der Controller die Daten per json zurück gibt und wie man die zurück gegebenen Daten auswertet.

Schritt 1 – per Ajax den Controller abfragen

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<div id="inhalt1"></div>
<div id="inhalt2"></div>
 
<script type="text/javascript">
ImageSwitch = {
 
    onPageLoad : function() {
        var id = 5;
        var requestUrl = '<?php echo Mage::getUrl('modul/index/action') ?>'; //HIER CONTROLLER ANGEBEN
 
        new Ajax.Request(requestUrl, {
            method : 'post',
            parameters  : 'pid='+id,
            onSuccess: this.onSuccessSend.bindAsEventListener(this),
            onFailure: this.onFailureSend.bindAsEventListener(this)
        });
 
    },
 
    onFailureSend : function(transport) {
        alert('Unable to connect to the server. Please try again.');
    },
 
    onSuccessSend : function(transport) {
        eval('var response = '+transport.responseText+';');
        $('inhalt1').update(response['inhalt1_html']);
        $('inhalt2').update(response['inhalt2_html']);
    }
 
};
 
ImageSwitch.onPageLoad();
</script>

Schritt 2 – Controller Inhalt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
 
class M28visions_Modul_IndexController extends Mage_Core_Controller_Front_Action
{
    /**
     * response html codes
     *
     */
    public function indexAction()
    {
        $pid = Mage::app()->getRequest()->getPost('pid'); 
 
        //response
        $response = array(
            'inhalt1_html' => '<p>INHALT1</p>',
            'inhalt2_html' => '<p>INHALT2</p>'
        );
 
        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
        $this->getResponse()->setHeader('Content-type', 'application/json');
    }
}

Viewing all articles
Browse latest Browse all 10