<input type = "button" class = "button" value = "提交" onclick="b()"/> //type=「submit」點擊onclick可能沒反應ajax
function b() {
$.ajax({
type : "POST", //提交方式
url : "http://localhost:8000/liuyan",//路徑
dataType: 'JSON', //異步傳輸問題可改爲‘JSONP’,不過提交方式要改爲」GET「json
data : {
"username":$("#username").val(),
"phone" : $("#phone").val(),
"grade" : $("#grade").val(),
"subject" : $("#subject").val(),數組
},//數據,這裏使用的是Json格式進行傳輸 這裏是形如id="username"的值,若是是name="username"要寫成app
"username":$("input[name='username']").val(),的格式異步
success: function (result) {
console.log(result);//打印服務端返回的數據(調試用)
},
error : function(result) {
alert("錯誤提示: " + result.status + " " + result.statusText);
}
});
}this
//後臺我用的symfony2url
$request = $this->getRequest();
$ret = '';
//$time=/DateTime();
if ('POST' == $request->getMethod()) {
$username = $request->get('username');
$phone = $request->get('phone');
$grade = $request->get('grade');//這個是下拉表得到數據是數組形式,因此作了一個switch判斷,以爲有更好的方法可是不會【捂臉】,會的話能夠留言或私我
$subject = $request->get('subject');
switch ($grade) {
case '0':
$grade='111';
break;
case '1':
$grade='222';
break;
case '2':
$grade='333';
break;
case '3':
$grade='444';
break;
}
switch ($subject) {
case '0':
$subject='數學';
break;
case '1':
$subject='語文';
break;
case '2':
$subject='英語';
break;
case '3':
$subject='文綜';
break;
case '4':
$subject='理綜';
break;
}
//$ret = $username.$phone.$grade.$subject;
//$ret = '姓名:'.$username.'<br/> 電話號碼:'.$phone.'<br/> 年級:'.$grade.'<br/> 科目:'.$subject.'<hr/>';
$user = new User();
$user->setUsername($username);
$user->setPhone($phone);
$user->setGrade($grade);
$user->setSubject($subject);
//$user->setCreatetime($time);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($user);
$em->flush();
//return new Response($ret);
$data = array(
'username' => $username,
'phone'=>$phone,
'grade'=>$grade,
'subject'=>$subject
);
return new Response(
json_encode($data,true),
200,
array('Content-Type' => 'application/json')
);
}
調試