2017-05-15 11 views
0

私はAPI GET関数を構築しました。フォームは、次のようになります。

<form action="/find" method="GET"> 
    <input type="text" name="Title" id="Title" value=""> 
    <input type="submit" value="Search"> 
</form> 

、これは上記のフォームを処理し、$form->get('Title')->getData()にテキストボックスから文字列を挿入する必要があり、私の関数です。しかし、私がブラウザを使ってGETしようとすると、それは私にSyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON dataを与えます。生データを見ると、次のようになります。

<pre class='xdebug-var-dump' dir='ltr'> 
<small>/home/vagrant/Code/symfony_awd/src/Blogsite/BooksBundle/Controller /BookController.php:29:</small><font color='#3465a4'>null</font> 
</pre>Google Volume Not Found 

私は変数がnullであることを理解していますが、なぜですか?ここでは、機能コードは次のとおりです。

public function findAction(Request $request) 
{ 
    $form = $this->createForm(null, ['csrf_protection' => false]) 
     ->add('Title', TextType::class) 
     ->add('Search', SubmitType::class) 
     ->getForm(); 

    $form->handleRequest($request); 

    var_dump($form->getData()); 

    if($form->isSubmitted() && $form->isValid()) { 
     $json = file_get_contents("https://www.googleapis.com/books/v1/volumes?q=".$form->get('Title')->getData()); 
     $response = json_decode($json, true); 

     if(array_key_exists('items', $response)){ 
      return $this->render('BlogsiteBooksBundle:Pages:results.html.twig', [ 
       'items' => $response['items'] 
      ]); 
     } else { 
      return new Response('Google did not have any items', 400); 
     } 
    } 

    return new Response('Google Book Not Found', 404); 
} 

答えて

1

デフォルトではフォームがPOSTを介して送信するデータを期待している、あなたはGETに、フォームのメソッドを設定する必要があります。

詳細について
$this->createForm(null, ['csrf_protection' => false, 'method' => 'GET']) 
    // ... 

を参照してください。 How to Change the Action and Method of a Form