通过 AJAX 传递类方法的参数



database.inc 中的通用添加记录函数.php

public function insert($data, $table) {
        $columns = "";
        $values = "";
        foreach ($data as $column =>$value) {
            $columns .= ($columns == "") ? "" : ", ";
            $columns .= $column;
            $values  .= ($values == "") ? "" : ", ";
            $values  .= $value;
        }
        $sql = "insert into $table ($columns) values ($values)";
        mysql_query($sql) or die(mysql_error());
        //return the ID of the user in the database.
        return mysql_insert_id();
    }

添加类别的方法:

<?php
include './database.inc.php';
class Categories{
    public function AddCategory(){
        $db = new Database();
        $b->connect();
        $db->insert($data, $table);
    }
}
?>

在插入方法中,$data是 $_POST 数组。这个函数工作正常,但我想传递 $_POST 数组不是通过 php,而是通过 ajax jquery。我将了解如何在 jquery 中获取帖子数组,但我的问题是我将如何在类别类中对这个特定的插入方法进行 ajax 调用,因为类别类中会有更多方法,如删除、更新等......我听说在 asp.net 有一个选项,他们可以在 URL: jquery ajax 的参数中传递页面名称和方法名称。

更新:这就是我调用该方法的方式:页 : 分类.php类 : 分类.php;

 <?php
        if (isset($_POST['submit'])) {
            unset($_POST['submit']);
            $_POST['DateAdded'];
            $_POST['DateAdded']=date("Y-m-d");
            // print_r($_POST);
            $Connection = new Database();
            $Connection->Connect();
            $Category = new Categories();
            $Category->AddCategory($_POST,"categories");
        }
        ?>
$(functiopn(){
    $('form#myForm').on('submit', function(e){
        e.preventDefault();
        var postData = $(this).serialize();
        $.post('categories.php', postData, function(data){
            // the server response will be available in "data" variable
        });
    });
});

在这里,myForm用作表单的id,因此请在表单中使用此id=myForm,或者如果有,请使用它而不是myForm

更新:如果您需要传递另一个参数,则可以在以下行var postData = $(this).serialize();之后立即添加另一个参数,例如

var postData = $(this).serialize()+"&method=insert"; // or "&method=update"

现在,每个表单字段(包括method)都可以_POST array and you can access any $_POST variable just like you do in php from your类别.php file because the form has been submitted to this脚本'。

我强烈建议您不要使用这种数据处理方式。你很容易受到SQL注入的影响。看看这些链接:

维基百科 - SQL 注入

SQL 注入示例

如果你知道自己在做什么,你可以通过使用 mysql_real_escape_string() 函数来防止这种情况。

$safeData = mysql_real_escape_string($unsafeData);

你的JSON可以被PHP的json_encode()解析。

$jsonArray = json_encode($jsonString);

这个功能非常严格,不要在你的JSON代码中犯错误!对于 AJAX 异步请求,应使用 jQuery.ajax,并将异步键设置为 true。GET (url) 参数应该在 URL 后面添加:

$.ajax({
    async: true,
    url: "script.php?page=bla&method=blabla",
    type: "POST",
    data: { <object to be sent via JSON here> }
});

您可以设置一个名为"方法"的 POST,在那里输入"插入"、"更新"等,以便在 php 文件中进行切换。

您需要通过 ajax 发送您将要使用的方法吗?好的,所以向 POST 发送一个名为方法的参数。

在 php 中,你应该做这样的事情:

$method = $_POST['metod'];
if ($method == 'insert'){
    //execute insert
} else if ($method == 'update'){
    // execute update
} //... etc

最新更新