在Magento 后台往往会想对某些页面写入JavaScript的需求,为了改变页面的内容,大多数的页面都在后端作处理就好,而有些页面像是Category>manage category裡的category做切换的时候是透过AJAX机制做传递,这时候就有写JavaScript的需求了。
1.如下图的红色框框,在切换category的时候执行JavaScript的程式码
2. 如下先找到这个档桉app\design\adminhtml\default\default\template\catalog\category\edit.phtml,再找到function updateContent() 裡 的 Onsuccess这一个程式区块,因为每次category再切换的时候是透过AJAX机制做传递,都会去跑这个区块,所以可在这个区块裡面撰写程式码。
function updateContent(url, params, refreshTree) { if (!params) { params = {}; } if (!params.form_key) { params.form_key = FORM_KEY; } toolbarToggle.stop(); /*if(params.node_name) { var currentNode = tree.getNodeById(tree.currentNodeId); currentNode.setText(params.node_name); }*/ var categoryContainer = $('category-edit-container'); var messagesContainer = $('messages'); var thisObj = this; new Ajax.Request(url + (url.match(new RegExp('\\?')) ? '&isAjax=true' : '?isAjax=true' ), { parameters: params, evalScripts: true, onComplete: function () { /** * This func depends on variables, that came in response, and were eval'ed in onSuccess() callback. * Since prototype's Element.update() evals javascripts in 10 msec, we should exec our func after it. */ setTimeout(function() { try { if (refreshTree) { thisObj.refreshTreeArea(); } toolbarToggle.start(); } catch (e) { alert(e.message); }; }, 25); }, onSuccess: function(transport) { try { if (transport.responseText.isJSON()) { var response = transport.responseText.evalJSON(); var needUpdate = true; if (response.error) { alert(response.message); needUpdate = false; } if(response.ajaxExpired && response.ajaxRedirect) { setLocation(response.ajaxRedirect); needUpdate = false; } if (needUpdate){ if (response.content){ $(categoryContainer).update(response.content); } if (response.messages){ $(messagesContainer).update(response.messages); } } } else { $(categoryContainer).update(transport.responseText); } onLandingPageSectionChanged(); } catch (e) { $(categoryContainer).update(transport.responseText); } } }); }
笔者的范例只限于manage category,如果其他页面的tab做切换也是用AJAX的机制,那要找到对应的那个onSuccess区块。