首頁  >  問答  >  主體

Opencart 2: 使用Ajax呼叫php文件

我想ajax呼叫我創建的系統/幫助程序的php文件,該文件調用在資料庫中添加優惠券的模型的方法。 php 檔案包含以下內容。

<?php
function coupon_for_acumba() {
            $this->load->model('total/coupon');

            echo $this->model_total_coupon->coupon_test();
        }

我創建了一個 js 文件,該文件在提交表單時進行 ajax 呼叫。文件中的腳本如下

let acumbaForm = document.querySelector('#form-acm_28955');
                acumbaForm.addEventListener('submit', function () {
                    setTimeout(function () {if (document.querySelector('.succes-alert-form-acm')) {
                        $.ajax({

                                url : '/system/helper/acumba.php',
                                type : 'POST',
                                success : function (result) {
                                console.log (result); // Here, you need to use response by PHP file.
                },
                    error : function () {
                        console.log ('error');
            }

                    });
                }}, 2000)
                    
                })

最後我用 $this->document->addScript('catalog/view/javascript/test1.js'); 在catalog/controller/common/header.php 中呼叫這個js檔案;

問題是,每次我提交表單時,我都會從 ajax 呼叫中收到一條錯誤訊息。你能告訴我我做錯了什麼嗎?

P粉153503989P粉153503989175 天前338

全部回覆(1)我來回復

  • P粉299174094

    P粉2991740942024-04-01 13:11:46

    OpenCart不允許直接從系統資料夾呼叫PHP檔案(檢查系統資料夾中的.htaccess檔案)。試著打開 https://yoursite/system/helper/acumba.php,你會得到 403 Forbidden。您必須使用路由來呼叫方法。

    url : '/system/helper/acumba.php', // wrong

    您必須修改 /catalog/controller/extension/total/coupon.php 並放入您的方法,然後在 JS 檔案中呼叫此方法。

    url : 'index.php?route=extension/total/coupon/coupon_for_acumba',

    回覆
    0
  • 取消回覆