如何在Silex中使用JQuery Ajax

时间:2016-06-22 09:49:48

标签: javascript jquery ajax silex

我试着理解Silex和JQuery是如何一起工作的。但是我不理解它,我希望你能帮助我。

我有一个twig-Template女巫包括AJAX电话。 我不明白如何将Ajax调用绑定到我的应用程序。

JS:

$(document).ready(function () {
/*
setInterval(function () {
    $.ajax({
        url: '/Chat/services/AjaxCom.php',
        type: 'GET',
        method: 'GET',
        data: {message: message},
        success: function () {
            console.log(data);
        },
        error: function () {php
            console.log('error');
        }
    });
    return false;
}, 100);
*/
$('form').submit(
    function (event) {

        event.preventDefault();
        var daten = $('#message').val();
        $.ajax({
            url: '/Chat/web/index.php',
            type: 'GET',
            data: {message: daten},
            success: function (daten) {
                alert(daten);
                $('#message').val(' ');
                //console.log(daten);
            },
            error: function () {
                console.log('error at writing');
            }

        });


    });

});

我用魔杖打电话给这堂课:

<?php
 namespace resources\services;
 resources\controller\UserOnline;
 use resources\objects\Message;
 use Silex\Application;

 /**
 * Class AjaxCom
 * @package resources\controller
 */
 class AjaxCom
 {

/**
 * @var array
 */
private $chatOutput = [];
/**
 * @var array
 */
private $userOutput = [];
/**
 * @var
 */
private $ddConnect;


/**
 * @return array
 */
public function getChatOutput()
{
    return $this->chatOutput;
}

/**
 * @return array
 */
public function getUserOutput()
{
    return $this->userOutput;
}


/**
 * AjaxCom constructor.
 * @param $datenbankVerbindung
 */
public function __construct($datenbankVerbindung)
{
    $this->ddConnect = $datenbankVerbindung;
}


/**
 * @return array
 */
public function showChatData()
{
    $posts = $this->ddConnect->fetchAll("SELECT * FROM messages");


    foreach ($posts as $post) {

        /*
         * post wird an die function buildMessageFromRow übergeben
        array chatOutput bekommt Die Id aus DB=>Message
        chatOutput[id objekt message] = objekt message d.h soviel id wie es gibt so viele Objekte gibt es. Jede zeile ist ein Objekt
        */
        $message = $this->buildMessagerFromRow($post);
        $this->chatOutput[$message->getId()] = $message;
    }

    return $this->getChatOutput();
}

/**
 * @return array
 */
public function showOnUser()
{
    $users = $this->ddConnect->fetchAll("SELECT * FROM user WHERE status='1'");
    foreach ($users as $userOnline) {
        $userOnline = $this->buildUserFromRow($userOnline);
        $this->userOutput[$userOnline->getId()] = $userOnline;

    }

    return $this->getUserOutput();

}

/**
 * @param $message
 * @param $writer
 */


public function writeChatDateInDb($message,$writer)
{
    $this->ddConnect->insert(
        'messages',
        array(
            'message' => $message,
            'writer' => $writer,
        )
    );


}

private function buildMessagerFromRow($rowSet)
{
    return new Message(
        $rowSet['id'],
        $rowSet['message'],
        $rowSet['writer']
    );
}
private function  buildUserFromRow($rowset){
    return new UserOnline(
        $rowset['id'],
        $rowset['name'],
        $rowset['password'],
        $rowset['status']
    );

}
}

有人可以解释一下,我如何连接JS和Class? 谢谢你的帮助 米莎

1 个答案:

答案 0 :(得分:3)

通常,您可以使用.htacces将所有内容路由到index.php。

<IfModule mod_rewrite.c>
    Options -MultiViews

    RewriteEngine On
    #RewriteBase /path/to/app
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [QSA,L]
</IfModule>

现在每个请求都应该路由到index.php。然后,您只需在index.php中添加路由或包含路由文件。

<强> JS

$('form').submit(
    function (event) {
        event.preventDefault();
        var daten = $('#message').val();
        $.ajax({
            url: '/chat',
            type: 'POST',
            data: {message: daten},
            success: function (daten) {
                alert(daten);
                $('#message').val(' ');
            },
            error: function () {
                console.log('error at writing');
            }
        });
    });
});

<强> PHP

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$app->post('/chat', function (Request $request) {
    $ajaxCom = new AjaxCom();
    $data = $request->get('message');
    $response = $ajaxCom->yourFunction($data);
    return $response;
});