Symfony2中的简单AJAX请求和响应

时间:2015-11-17 16:34:49

标签: javascript php ajax symfony twig

我在Symfony中有一个“创建”表单,并且通过在textarea中输入一些信息,控制器应该只处理请求并对其进行相应的响应。

AJAX调用是在树枝模板中进行的:

{% block content_foot_script %}
<script>
    function fetchData() {
        xhttp = new XMLHttpRequest();
        xhttp.open("POST", "{{ path('receiptFetchSystem') }}", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        var data = $("#admin_store_receipt_receiptbundle_receipt_objects").val();
        xhttp.send('items=' + data);

        xhttp.onreadystatechange = function() {
            if (xhttp.success && xhttp.code == 200) {
                document.getElementById('demo').innerHTML = xhttp.responseText;
            }
        }
    }
</script>
{% endblock %}

并且ReceiptFetchController处理请求:

<?php

namespace Admin\Store\Receipt\ReceiptBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class ReceiptFetchController extends Controller
{
    /**
     * @Route("/call", name="receiptFetchSystem")
     * @Template()
     */
    public function callAction()
    {
        $request = $this->container->get('request');
        $data = $request->request->get('items');

        $response = array("code" => 200, "success" => true);
        return new Response($response);    
    }

}

好吧,正如预期的那样,我没有得到回应:)

祝你好运

1 个答案:

答案 0 :(得分:1)

嗯,我通过更改一些代码使其工作,这里是:

ReceiptFetchController.php:

<?php

namespace Admin\Store\Receipt\ReceiptBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;

class ReceiptFetchController extends Controller
{
    /**
     * @Route("/call", name="receiptFetchSystem")
     * @Template()
     */
    public function callAction()
    {
        $request = $this->container->get('request');

        $items = $request->request->get('items');
        $response = new Response();
        $response->headers->set('Content-Type', 'application/json');

        $itemsList = preg_split('/\r\n|[\r\n]/', $items);

        $em = $this->getDoctrine()->getRepository('AdminStoreProductProductBundle:Product');
        $productsList = array();
        foreach ($itemsList as $key){
            $product =$em->findOneBy(array('barCode' => $key));
            if ($product) {
                $productDetail['Price'] = $product->getSalesPrice();
                $productDetail['Type'] = $product->getType()->getSlugify();
                $productDetail['Name'] = $product->getName();
                $productsList[] = $productDetail;
            }

        }

        $response->setContent(json_encode($productsList));
        return $response;
    }

}

这是视图文件:

{% block content_head_script %}
    <script>
        function fetchData() {
            xhttp = new XMLHttpRequest();
            var data = $("#admin_store_receipt_receiptbundle_receipt_objects").val();
            xhttp.open("POST", "{{ path('receiptFetchSystem') }}", true);
            xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhttp.send('items=' + (data));

            xhttp.onreadystatechange = function () {
                if (xhttp.readyState == 4 && xhttp.status == 200) {
                    TableGenerator(xhttp.responseText);
                }
            }
        }

        function TableGenerator(response) {
            var totalPrice = 0;
            var arr = JSON.parse(response);
            var i;
            var out = "";

            for(i = 0; i < arr.length; i++) {
                out += "<tr><td>" +
                        arr[i].Price +
                        "</td><td dir='ltr'>" +
                        arr[i].Type +
                        "</td><td>" +
                        arr[i].Name +
                        "</td></tr>";

                totalPrice += arr[i].Price;
            }
            out += "<tr><td colspan='2' dir='ltr'><strong>جمع کل</strong></td><td>" + totalPrice + "</td></tr>";
            $('#tableBody').html(out);
        }
    </script>
{% endblock %}