【发布时间】:2015-01-01 13:49:51
【问题描述】:
我正在尝试通过 ajax 调用提交使用 symfony2 创建的表单。 我知道那里有很多教程,但我认为我做的一切都是正确的,但仍然无法让它发挥作用。
这是我在控制器中的代码:
/**
* @Route("/preferences", name="_mybundle_preferences")
* @Template()
*/
public function preferencesAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$allprefs = $em->getRepository('MyBundle:MyPrefs')
->findAllPrefs();
// Creating the form
$defaultData = array();
$formpref = $this->container
->get('form.factory')
->createNamedBuilder(
'formpref',
'form',
$defaultData,
array('validation_groups' => array())
);
// Input the search field
// (will be connected to a jQuery function to filter results)
$formpref->add('search', 'search', array( 'mapped' => false) );
// Populate the list of choice fields where the user can select its
// preferences
foreach ( $allprefs as $mypref)
{
$fieldname = $mypref->getId();
$formpref->add($fieldname, 'choice', array(
'choices' => array(
'3' => 'Very',
'2' => 'Quite',
'1' => 'Poor',
'0' => 'None'
),
'expanded' => false,
'label' => $mypref->getName(),
));
}
// Just temporary, I want to remove it through ajax
$formpref->add('send', 'submit');
// Get the form
$formpref = $formpref->getForm();
// Handle the request
$formpref->handleRequest($request);
if ($formpref->isValid()) {
// do stuff
$response = array("success" => true);
return new Response(json_encode($response));
}
$result = array(
'forms' => $formpref->createView(),
);
return $result;
}
在我的树枝上:
<div id="div1" data-path="{{path('_mybundle_preferences')}}">
</div>
{{ form(forms) }}
还有 jQuery 脚本
$("select").change( function(){
// I am using an array to check how many output requests I already made
var myArray = [];
myArray.push( 1 );
$("#div1").html("Saving...");
$.ajax({
type: "POST",
url: $('#div1').data('path'),
data: $("#formpref").serialize() ,
async: true,
dataType: "json",
success: function(response) {
myArray.pop();
if (myArray.length === 0) {
$("#div1").html("All changes saved");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
console.log('Error : ' + errorThrown);
},
});
return false;
});
通过代码中插入的一些 file_put_contents(此处未显示)我可以 看到 $formpref->isValid() 调用永远不会在表单返回 true 时 使用 ajax 提交,但使用普通提交按钮提交时可以正常工作。
我也尝试将结果发送到不同的路线,但结果相同......
我做错了什么?我在兜圈子……
【问题讨论】: