javascript - Symfony 3.4 如何将 Javascript 数据传递给 Controller ​​?

标签 javascript database controller symfony-3.4

我想在数据库中存储一个包含动态内容的对象。我有一个输入框,人们可以在其中输入文字。我希望输入字段的内容是对象的标题。我可以通过 Javascript 获取内容并通过 Controller 保存对象。但我不知道如何将数据从 Javascript 传递到 Controller 。

这是我已经尝试过的:

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 :

<?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());
    }
}

最佳答案

我自己想出了解决方案 :D。我不知道我的函数中需要 Request,现在也知道它的作用。

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());
    }
}

我更改/添加的内容:

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

关于javascript - Symfony 3.4 如何将 Javascript 数据传递给 Controller ​​?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58977446/

相关文章:

mysql - Rails 生产中的 "Connecting to database specified by database.yml"

java - 从 spring Controller 返回 json 数组

cocoa-touch - 第二个 View 上的详细信息按钮

javascript - Java 脚本未在我的应用程序中执行

javascript - 在动态生成的表格中居中输入

java - 线程安全和性能 - 与数据库访问同步的方法

ruby-on-rails - rails : Prevent duplicate inserts due to pressing back button and save again

javascript - Node.js 服务器重启基础知识错误处理

javascript - 如何从 grunt 任务运行 node_modules 中的脚本?

ruby-on-rails - 在用户数据库中包含帐户信息