【问题标题】:How to define URL property for ajax call in Magento?如何在 Magento 中为 ajax 调用定义 URL 属性?
【发布时间】:2016-06-16 09:00:42
【问题描述】:

我正在使用 Magento 进行开发。我需要对同一页面进行 ajax 调用以从相关的 php 函数中获取一些详细信息。当我在开发人员工具中检查时,在网络选项卡下,对当前页面进行了调用,但它显示以下错误:

Invalid URL: adminpteb/efund/efund.phtml

efund.phtml 是发起 ajax 调用的页面,要调用的 php 函数也位于同一页面内。 Magento 是否有自己的方式通过 ajax 获取 php 脚本?

参考此链接:Using Basic AJAX calls within Magento

我这样定义了 URl:url:/adminpteb/efund/efund.phtml,但仍然是同样的错误。

ajax 提醒'完成'并且正确的功能被拾取。但是函数 1 返回的值没有到达 ajax。 我的脚本:

$.ajax({
      method: "GET",
      url: "efund.phtml",
      data: { function_to_call: 0, id: cl[3] }
    }).fail(function() {
      alert( "error" );
    }).always(function() {
       alert( "complete" );
    }).done(function( msg ) {
        var obj = jQuery.parseJSON( msg );
        alert( "ID obtained from server is " + obj.id );
      });

PHP 脚本

switch ($_GET['function_to_call']) 
     {

         case 0:
         {   
               function1($_GET['id']);
               break;
         }

        case 1: 
        {
              function2();
              break;
        }
        default: break;

     }



        function function1() {
            echo "ID= ".$_GET['id'];
             return json_encode(array ( "id" => $param ) );
        }
        function function2() {
             echo "This is function 2";
    }

【问题讨论】:

    标签: php jquery ajax magento


    【解决方案1】:

    您可以通过以下代码在magento中获取当前页面URL

    $currentUrl = Mage::helper('core/url')->getCurrentUrl();
    $url = Mage::getSingleton('core/url')->parseUrl($currentUrl);
    $path = $url->getPath();
    

    然后将此网址传递给您的 ajax 调用

    $.ajax({
        method: "GET",
        url: '<?php echo path; ?>',
        data: {function_to_call: 0, id: cl[3]}
    }).fail(function () {
        alert("error");
    }).always(function () {
        alert("complete");
    }).done(function (msg) {
        var obj = jQuery.parseJSON(msg);
        alert("ID obtained from server is " + obj.id);
    });
    

    【讨论】:

    • 它调用文件夹名称'efund'。但是没有从函数返回值。
    • 它必须提醒这个:alert("从服务器获取的ID是" + obj.id);
    • 它不会提醒这一点。因为每次ajax调用它都会渲染整个页面。所以你的obj.id 不会执行。试试alert(msg)。我建议您通过控制器调用 ajax。这是一种标准方法。
    • 是的,它呈现整个页面。我假设它不调用函数 1?那么ajax如何返回'完成'?如果我仍然需要调用 php 函数并从中取回值,它们的方式是什么?
    • 完成此类任务的最佳方法是创建一个自定义模块并继承您想要的功能,然后将您的 ajax 代码调用到控制器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-04
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    相关资源
    最近更新 更多