如何使用ajax jQuery将数据发布到php文件并将其保存在json文件中?

时间:2015-07-09 09:21:15

标签: javascript php jquery ajax json

嗨我的申请有问题。我使用xampp来测试我的应用程序。我在htdocs中有两个文件夹:

文件夹客户端:这是index.html和带有js文件的底层文件夹。

文件夹服务器:这里我有一个server.php文件和data.json文件。

我从朋友那里得到了代码,我知道为什么它不起作用,但我不知道出了什么问题。

应用程序必须创建一个用户并将此关于jQuery Ajax发送到php文件,这将数据保存在json文件中。

如果我点击按钮没有任何反应:(

这是index.html:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
    <script src="js/script.js"></script>
</head>
<body>
    <button type="button" id="add">Mitarbeiter hinzufügen</button>
    <div id="TableContent"></div>
</body>
</html>

这是javascript:

$(document).ready(function() {
    // Fill table with data from server on first load
    $.ajax({
        type: "GET",
        url: "../server/server.php",
        data: {
            method: "all"
        },
        success: function(content) {
            // Create table content from server data
            var table = $.makeTable($.parseJSON(content));
            // Append table data to table element in index.html
            $(table).appendTo("#TableContent");
        }
    });

    // Add user
    $('#add').on('click', function(){

        alert("Ein neuer Benutzer wird erstellt");

        console.log('add user');
        $.ajax({
            type: "POST",
            url: "../server/server.php",
            data: {
                vorname: "Wowa",
                nachname: "Tarasov"
            },
            success: function(content) {
                alert(content);
            }
        });
    });

    // Delete user
    $(document).on("click", "button.remove" , function() {
        // Send DELETE request to server
        // Id of a user
        console.log($(this).attr('value'));
        console.log('delete');

        $.ajax({
            type: "DELETE",
            url: "../server/server.php",
            data: {
                method: "all"
            },
            success: function(content) {
                // content is a response from server
                // Don't forgive to update the table after adding of a user
            }
        });
    });

    // Function to generate a table from a json array
    // It will not work, if you pass an object to it
    $.makeTable = function (mydata) {
        var table = $('<table border=1>');
        var tblHeader = "<tr>";
        for (var k in mydata[0]) tblHeader += "<th>" + k + "</th>";
        tblHeader += "<th>Aktionen</th>"
        tblHeader += "</tr>";
        $(tblHeader).appendTo(table);
        $.each(mydata, function (index, value) {
            var TableRow = "<tr>";
            var idx = value.id;
            $.each(value, function (key, val) {
                TableRow += "<td>" + val + "</td>";
            });
            TableRow += '<td><button class="remove" value=' + idx + '>Delete</button></td>';
            TableRow += "</tr>";
            $(table).append(TableRow);
        });
        return ($(table));
    };
});

这是php:

<?php

class Request
{
    public $url_elements;
    public $methode;
    public $parameters;

    public function __construct()
    {
        $this->methode = $_SERVER['REQUEST_METHOD'];
        if(isset($_SERVER['PATH_INFO'])) $this->url_elements = explode('/', $_SERVER['PATH_INFO']);
        else $this->url_elements = array();
        // get GET/DELETE or POST/PUT parameters
        $parameters = array();
        if (isset($_SERVER['QUERY_STRING'])) {  // get GET/DELETE parameters
            parse_str($_SERVER['QUERY_STRING'], $parameters);
        }
        $body = file_get_contents("php://input"); // get POST/PUT request body
        parse_str($body, $postvars);
        foreach ($postvars as $field => $value) {
            $parameters[$field] = $value; // overwrite GET/DELETE parameteres
        }

        $this->parameters = $parameters;
    }
}

/**
 * Class RequestHandler handles GET, POST, PUT and DELETE HTTP-requests from clients
 */
class RequestHandler
{
    /**
     * Read method
     */
    public function getAction($request)
    {
        $data = $request->parameters;


        switch ($request->parameters['method']) {
            case 'all':

                $person1 = new stdClass;
                $person1->Id = 1;
                $person1->Vorname = "Max";
                $person1->Nachname = "Mustermann";
                $person1->Geburtstag = "11.11.1980";
                $person1->Abteilung = "Personal";

                $person2 = new stdClass;
                $person2->Id = 2;
                $person2->Vorname = "Sabine";
                $person2->Nachname = "Musterfrau";
                $person2->Geburtstag = "05.12.1989";
                $person2->Abteilung = "Finanzen";

                // Add person in array
                $persons = array();
                array_push($persons, $person1);
                array_push($persons, $person2);

                // Encode array to json string and return to client
                return json_encode($persons);
                break;
            case 'single_user':
                break;
            default: // do nothing, this is not a supported action
                break;
        }
        return json_encode($data);
    }

    /**
     * Delete method
     */
    public function deleteAction($request)
    {
        $data = $request->parameters;
        return json_encode($data);
    }

    /**
     * Create method
     */
    public function postAction($request)
    {
        $data = $request->parameters;
        return json_encode($data);
    }

    /**
     * Update method
     */
    public function putAction($request)
    {
        $data = $request->parameters;
        return json_encode($data);
    }
}

$request = new Request();
$handler = new RequestHandler();
$action = strtolower($request->methode) . 'Action';
$result = $handler->$action($request);
print_r($result);

0 个答案:

没有答案