如何使用带有ajax的JsonResponse

时间:2015-12-03 14:47:47

标签: javascript php jquery ajax symfony

我正在使用Symfony2并执行Ajax调用来处理表单。我遇到的问题是,通过使用返回我的JsonResponse,驱动程序告诉我该值未定义。我想知道我做错了什么来解决这个问题,并且如果以某种方式可以将错误返回到表单字段以从Ajax验证可以在不刷新页面的情况下在表单中显示失败。

控制器:

public function createAction(Request $request){

$entity = new Student();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);

if ($form->isValid()) {
    $em = $this->getDoctrine()->getManager();
    $em->persist($entity);
    $em->flush();

    return new JsonResponse(array('message' => 'Success!'), 200);
 }

    return $this->render('BackendBundle:Student:new.html.twig', array(
    'entity' => $entity,
    'form'   => $form->createView(),
 ));
}

Ajax电话:

$('.form_student').submit(function(event) {
 event.preventDefault();

  $.ajax({
  type: 'POST',
  url: Routing.generate('student_create'),
  data: $(this).serialize(),

  success: function(response) {

    alert(response.message);

  },
  error: function (xhr, desc, err){

    alert("error");
  }
 })
  return false;
});

3 个答案:

答案 0 :(得分:1)

使用ajax,返回将无法正常工作

return new JsonResponse(array('message' => 'Success!'), 200);

您应该使用PHP echo打印该值,以便在ajax成功回调中使用它,例如

echo new JsonResponse(array('message' => 'Success!'), 200);

答案 1 :(得分:1)

您需要以不同于常规HTML请求的方式处理XMLHttpRequests。

目前,在创建XMLHttpRequest但表单失败时,将再次呈现整个页面(使用"成功"状态代码),但您只想返回带有消息和&#的响应34;失败"状态代码。

以下内容可以为您提供帮助。

public function createAction(Request $request)
{
    // if request is XmlHttpRequest (AJAX) but not a POSt, throw an exception
    if ($request->isXmlHttpRequest() && !$request->isMethod(Request::METHOD_POST)) {
        throw new HttpException('XMLHttpRequests/AJAX calls must be POSTed');
    }

    $entity = new Student();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        // if the form was successful and the call was an AJAX request
        // respond with a JSON Response (with a 201/created status code)
        if ($request->isXmlHttpRequest()) {
            return new JsonResponse(array('message' => 'Success!'), 201);
        }

        // If the form was successful and the call was HTTP
        // redirect to "show student"
        return $this->redirect('student_show', array('id' => $entity->getId()));
    }

    // if request was an AJAX call and (obviously) the form was not valid
    // return message about form failure
    // (with a 400/Bad Request status code)
    if ($request->isMethod(Request::METHOD_POST)) {
        return new JsonResponse(array('message' => 'failed due to form errors'), 400);
        // you could also loop through the form errors to create an array, use a custom 
        // form -> errors array transformer or use the @fos_rest.view_handler to output
        // your form errors
    }

    return $this->render('BackendBundle:Student:new.html.twig', array(
        'entity' => $entity,
        'form'   => $form->createView(),
    ));
}

<强>更新

javascript 应该像这样工作。

$('.form_student').submit(function(event) {
    event.preventDefault();

    $.ajax({
        type: 'POST',
        url: Routing.generate('student_create'),
        data: $(this).serialize(),
        dataType: 'json',

        // if "student_create" returns a 2** status code
        success: function(response) {
            // should return "Success!"
            alert(response.message);
        },

        // if "student_create" returns a non-2** status code
        error: function (xhr, desc, err){
            // if the response was parsed to json and has a message key
            if (xhr.responseJSON && xhr.responseJSON.message) {
                alert(xhr.responseJSON.message);
            // otherwise use the status text
            } else {
                alert(desc);
            }
        }
    });

    return false;
});

答案 2 :(得分:0)

您需要采取两项措施:

1。动作节目

显示操作应该处理表单的界面。例如:

public function showAction(Request $request){

    $entity = new Student();
    $form = $this->createCreateForm($entity);

    return $this->render('BackendBundle:Student:new.html.twig', array(
        'entity' => $entity,
        'form'   => $form->createView(),
    ));
}

2。动作句柄保存

动作保存应该在ajax请求保存数据时处理。例如:

public function createAction(Request $request)
{
    //get all data post
    $data = $request->request->all();
    extract($data, EXTR_PREFIX_SAME, "wddx");
    // if you want to see the result uncoment below
    // dump($data); // uncomment this to see data

    //$id = $data['id'];
    //$name = $data['name'];

    $student = new Student();
    //$student->.... = ... // set your field
    //...
    //...


    try {
        // try save entity
        $em = $this->getDoctrine()->getManager();
        $em->persist($student);
        $em->flush();
    } catch (\Exception $e) {
        // set your error message ...
    }
}

注意:

记住更改url: Routing.generate('student_create')指向保存句柄