特定功能的ajax的url参数

时间:2017-09-05 11:26:47

标签: php jquery

我想将ajax的url参数设置为类的函数并返回该函数的值,但我的问题似乎无法访问函数而且没有返回

这是我的剧本:

$('#send').click(function (e) { //event added
    e.preventDefault(); //prevent normal for submit
    $.ajax({
        type:'post',
        url:'localhost/shapeproject/controllers/Square/getArea',
        data:{'edge':edge},
        success:(function (response) {
            alert(response);
        })
    });
});

这是我的班级:

<?php
class Square extends Shape
{
    private $edge;

    function __construct()
    {
        $this->edge = $_POST['edge'];
    }

    public function getArea()
    {
        return $this->edge * $this->edge;
    }

    public function getPerimeter()
    {
        return $this->edge * 4;
    }
}

3 个答案:

答案 0 :(得分:1)

但您没有设置任何数据......将data添加到jquery函数;

$.ajax({
    type:'post',
    url:'localhost/shapeproject/controllers/Square/getArea',
    data: { edge: 'xyz' },
    success:(function (response) {
        alert(response);
    })
});

答案 1 :(得分:1)

您可以添加页面并将其命名为ajax_handle.php。 然后链接到你的ajax代码中的那个页面

$('#send').click(function (e) { //event added
    e.preventDefault(); //prevent normal for submit
    $.ajax({
        type:'post',
        url:'ajax_handle.php',
        data:{'edge':edge, getArea: true},
        success:(function (response) {
            alert(response);
        })
    });
});

现在在你的ajax_handle.php中你可以编写这段代码。

if(isset($_POST['getArea']) && $_POST['getArea'] == true)
{
    $obj = new Square();
    $obj->getArea();
}

答案 2 :(得分:0)

您必须有一个前端控制器来管理此过程。

例如:在index.php目录中创建一个名为shapeproject的文件。

然后,您可以从$_SERVER['REQUEST_URI']中提取控制器和函数名称。

您可能需要使用一些.htaccess指令,如下例所示:

RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php

详细了解前置控制器:An Introduction to the Front Controller Pattern