[symfony] get the json from request and use it to create the entity
<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() {
var json = {
"userName": "test",
"msg": "test"
}
$.ajax({
url: 'http://test123/api/add',
/*
data: {
"name":"123",
"age":"50"
},
*/
data: JSON.stringify(json),
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>
/**
* Add New Message
* @Route("api/add", name="apiAdd")
* @Method("POST")
*/
public function createActioniAPI(Request $request)
{
$message = new Message();
/*
$message = $request->get('data');
$name = $message["userName"];
$msg = $message["msg"];
*/
$content = $request->getContent();
$data = json_decode($content, true);
$u = $data['userName'];
$m = $data['msg'];
// $name = "testName";
// $msg = "testMessage";
$publishAt = new \DateTime('now', new \DateTimeZone('Asia/Taipei'));
$message = new Message();
$message->setUserName($u);
$message->setMsg($m);
$message->setPublishedAt($publishAt);
$response = new Response();
// $response->setContent($request);
/*
$content = $request->getContent();
$data = json_decode($content, true);
$u = $data['userName'];
$m = $data['msg'];
*/
// $j = json_decode('{"indices":[1,2,6]}', true);
$response->setContent("content-type: " . gettype($content) . " \$content: " .$content . " userName " . $u);
$response->headers->set('Content-Type', 'application/json');
$response->headers->set('Access-Control-Allow-Origin', '*');
$em = $this->getDoctrine()->getManager();
$em->persist($message);
$em->flush();
$redirectArray = ['id' => $message->getId()];
$filename = "/home/eric_tu/eric_tu/request.log";
$file = fopen( $filename, "w" );
if( $file == false ) {
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple test\n" . $content . $response . $request);
fclose( $file );
// $re = ['hi' => '123'];
// $j = $re['hi'];
// dump($j['indices'][0]);
// dump($request);
return $response;
// return $this->redirectToRoute('list', $redirectArray);
}
留言
張貼留言