简体   繁体   English

Symfony 3.4 如何将 Javascript 数据传递给 controller?

[英]Symfony 3.4 how to pass Javascript data to controller?

I want to store an object in the database with dynamic content in it.我想在数据库中存储一个 object ,其中包含动态内容。 I have an input field where people can write text inside.我有一个输入字段,人们可以在其中写文本。 I want the content of the input field to be the title of the object.我希望输入字段的内容是 object 的标题。 I can get the content trough Javascript and save an object trough the controller.我可以通过 Javascript 获取内容,并通过 controller 保存 object。 But I can't figure out how to pass the data from Javascript to the controller.但我不知道如何将数据从 Javascript 传递到 controller。

This is what I have and tried:这是我已经尝试过的:

Javascript: Javascript:


//Content I need to store
var outputOfInputField = document.getElementById("inputCategory").value;

//Ajax call with JSON that I think I need for pass data to controller.
$.ajax({
   url : '/createcategory',
   type: "POST",
   data: {
      'output': outputOfInputField
   },
   success : function (data) {
      console.log("SUCCES" + data);
   },
   error   : function () {
      console.log("ERROR");
   }
});

Controller: Controller:

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\User as User;
use Appbundle\Entity\Category as Category;


class HomePageController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */

    public function getData() {
       ...//Not important
    }


    /**
     *  @Route("/create-category", name="newCat")
    */
    public function createObject() {

        //Tried to get the data from JSON file here, dont know what it does and also does not work, gives me an error... Saying i need a use on top of this controller. If I add it it still dont work.

        // $form = $this->get('form.factory')->createBuilder(FormType::class)
        //     ->add('ndf', CollectionType::class, array(
        //         'entry_type' => NoteDeFraisType::class,
        //         'label' => false,
        //         'allow_add' => true,
        //         'allow_delete' => true,
        //     ))
        //     ->getForm();

        //     if ($request->isXMLHttpRequest()) {
        //         $output = $request->request->get('output');
        //         echo $output;
        //         var_dump($output);
        //         print_r($output);
        //     }




        //This is where I create the object and store it in the database.
        $category = $this->getDoctrine()
            ->getRepository('AppBundle:Category')
            ->findall();

        $category = new Category();

        //At the $outputFromJavascript should be the place where my javascript content has to be. Now it does not work, it only works when I put a hardcoded text in it like this "Hello".
        $category->setTitle($outputFromJavascript);

        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($category);
        $em->flush();

        return new Response('Created product id '.$category->getId());
    }
}

Hope I kept the question clear:)希望我把问题说清楚:)

I figured out the solution myself:D.我自己想出了解决方案:D。 I did not know I need Request in my function, also now know what it does.我不知道我的 function 中需要 Request,现在也知道它的作用。

The javascript stays the same, the controller is now looking like this: javascript 保持不变,controller 现在看起来像这样:


<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\User as User;
use Appbundle\Entity\Category as Category;


class HomePageController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */

    public function getData() {
       //...
    }

    /**
     *  @Route("/create-category", name="newCat")
    */
    public function createCategory(Request $request) {
        // dump($request);
        // dump($request->request->get('output'));

        $output = $request->request->get('output');

        $category = $this->getDoctrine()
            ->getRepository('AppBundle:Category')
            ->findall();

        $category = new Category();
        $category->setTitle($output);

        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($category);
        $em->flush();

        return new Response('Created product id '.$category->getId());
    }
}

What I changed/added:我更改/添加的内容:

//Added Request $request
public function createCategory(Request $request) {
//Added line for getting the output of ajax/json post.
$output = $request->request->get('output');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM