Markdown

[PHP] POST JSON BY AJAX

<DOCTYPE>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>TEST CATCH API</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var Submit = function() {

$.ajax({
url: 'http://test123/api/add',
data: {
"name":"123",
"age":"50"
},
type: "POST",
dataType: 'text',

success: function(msg) {
// alert(msg);
console.log(msg)
},

error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});

}
</script>
</head>

<body>
<form id="sentToBack">
<input type="text" name="Text" />
<input type="button" value="送出" onClick="Submit()" />
</form>
</body>

</html>

---


```
|327     /**~
|328      * Add New Message~
|329      * @Route("api/add", name="apiAdd")~
|330      * @Method("POST")~
|331      */~
|332     public function createActioniAPI(Request $request)~
|333     {~
-334         $message = new Message();~
 335 /*~
-336         $message = $request->get('data');~
2337         $name = $message["userName"];~
2338         $msg = $message["msg"];~
 339 */~
-340           $name = "testName";~
2341           $msg = "testMessage";~
2342         $publishAt = new \DateTime('now', new \DateTimeZone('Asia/Taipei'));~
2343 ~
2344            $message = new Message();~
2345 ~
2346            $message->setUserName($name);~
2347 ~
2348            $message->setMsg($msg);~
2349 ~
2350            $message->setPublishedAt($publishAt);~
2351 ~
2352         $response = new Response();~
2353 ~
 354   //      $response->setContent($request);~
-355         $content = $request->getContent();~
2356         $response->setContent("type: " . gettype($content) . "   \$content: " .$content);~
2357         $response->headers->set('Content-Type', 'application/json');~
2358 ~
2359         $response->headers->set('Access-Control-Allow-Origin', '*');~
2360 ~
2361         $em = $this->getDoctrine()->getManager();~
2362 ~
2363         $em->persist($message);~
2364 ~
2365         $em->flush();~
2366 ~
2367         $redirectArray = ['id' => $message->getId()];~
2368 ~
2369         $filename = "/home/eric_tu/eric_tu/request.log";~
2370         $file = fopen( $filename, "w" );~
2371 ~
2372         if( $file == false ) {~
-373             echo ( "Error in opening new file" );~
3374             exit();~
2375         }~
2376         fwrite( $file, "This is  a simple test\n" );~
2377         fclose( $file );~
2378 ~                                                                                                                            
2379         return $response;~
 380 ~
 381   //      return $this->redirectToRoute('list', $redirectArray);
}
```


在瀏覽器的 console 可以看到 : type: string   $content: name=123&age=50

接下來要做的就是 發request 近來 取得usermane 跟 message,
然後用 set 設定接著再flush 進去

成功之後 可以再測試端模擬ajax行為做測試

想法:
似乎也可以利用ajax 傳遞 router參數,
這樣前端會做的方便一點

https://stackoverflow.com/questions/23329478/send-post-data-with-ajax-withtout-form-to-a-symfony2-controller-in-json-forma

留言