使用ajax发布表单时获取html作为响应

问题描述 投票:0回答:1

我的错误应该很容易被一个更有经验的开发人员发现,所以这里希望你可以帮助我。

我有一个在控制器方法中创建的表单:

public function manage_groups(
    Request $request,
    Globals $globals,
    $_locale,
    $_id
) {
    // manage group logic omitted
    // ...
    $newPhoto = new Photo();
    $photoForm = $this->createForm(PhotoType::class, $newPhoto, array(
        'action' => $this->generateUrl('admin_upload_foto'),
        'method' => 'POST'
    ));
    // ...

    return $this->render('admin/groups/manage_groups.html.twig', array(            
        'photoform'             => $photoForm->createView()
        // ...
    ));
}

动作URL指向此控制器方法:

/**
 * Matches /admin/upload/foto
 * @Route(
 *     "/upload/foto",
 *     name="admin_upload_foto")
 * @Method({"POST"})
 * @return JsonResponse
 */
public function upload_photo(
    Request $request
) {
    $response = new JsonResponse();

    $newPhoto = new Fotos();
    $photoForm = $this->createForm(PhotoType::class, $newPhoto);
    $photoForm->handleRequest($request);

    if ($photoForm->isSubmitted() && $photoForm->isValid()) {
        // $file stores the uploaded PDF file
        $file = $newPhoto->getFile();

        // Generate a unique name for the file before saving it
        $fileName = md5(uniqid()).'.'.$file->guessExtension();
        // Move the file to the directory where activity photos are stored
        $file->move(
            $this->getParameter('activity_photo_directory'),
            $fileName
        );

        // Update the 'brochure' property to store the PDF file name
        // instead of its contents
        $newPhoto->setFile($this->getParameter('activity_photo_reletive_directory')."/".$fileName);
        $em = $this->getDoctrine()->getManager();
        $em->persist($newPhoto);
        $em->flush();
        $response->setStatusCode(200);
        $response->setContent(array("result" => 1, "newPhoto" => $newPhoto->getFile(), "category" => $newPhoto->getCategorie()));
    } else if ($photoForm->isSubmitted()) {
        $errors = array();
        $errors[] = $photoForm['categorie']->getErrors();
        $errors[] = $photoForm['file']->getErrors();
        $response->setStatusCode(400);
        $response->setContent(array("result" => 0, "errors" => $errors));
    } else {
        $response->setStatusCode(400);
        $response->setContent(array("result" => 0, "errors" => "Het foto-formulier is niet verzonden naar de server"));
    }
    $response->headers->set('Content-Type', 'application/json');
    return $response;
}

页面正确加载,表单可以使用以下ajax提交:

    dialogUploadPhoto.find('form').submit((event) => {
        // const formData = new FormData();
        // formData.append('photo-file', dialogUploadPhoto.find('input[type="file"]')[0].files[0]);
        // formData.append('photo-categorie', $('photo-categorie').val());
        const formData = new FormData(this);
        // formData.append('photo-categorie', dialogUploadPhoto.find('photo-categorie').val());
        // formData.append('photo-file', dialogUploadPhoto.find('input[type="file"]')[0].files[0]);
        console.log(' >> >> >> Uploading image', formData);
        event.preventDefault();
        $.ajax({
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            data: $(this).serialize(), // formData,
            cache: false,
            success: function(response) {
                console.log(' >> >> Upload successful: ', response);

                dialogSelectPhoto.find("div:first-child").prepend(
                    '<a href="#" class="btn btn-default" ' +
                    'onclick="handleImageClick(\''+response.newPhoto+'\');">' +
                    '<img src="'+window.location.origin+'/'+response.newPhoto+'" width="250" height="auto" />' +
                    '</a>');

                dialogUploadPhoto.dialog( "close" );
            },
            error: function (xhr, desc, err){
                let errors = 'Unknown error occurred';
                if (xhr.responseJSON.errors instanceof Array) {
                    errors = "<ul>";
                    if (xhr.responseJSON.errors[0]) {
                        errors += "<li>Categorie: " + xhr.responseJSON.errors[0] + "</li>";
                    }
                    if (xhr.responseJSON.errors[1]) {
                        errors += "<li>Foto: " + xhr.responseJSON.errors[1] + "</li>";
                    }
                    errors += "</ul>";
                } else {
                    errors = xhr.responseJSON.errors;
                }
                dialogUploadPhotoError.find("#dialogUploadPhotoErrorMessage").html(errors);
                dialogUploadPhotoError.dialog('open');
            }
        });
    });

我已经尝试了几件事,ajax在普通html中返回页面成功,但是没有调用控制器方法(断点未命中)

按要求这是tcp包响应enter image description here的屏幕截图

我错过了什么?

php ajax symfony post symfony4
1个回答
2
投票

我不确定,但看起来你的ajax调用是你的函数manage_groups()

在你的ajax电话中:

url: $(this).attr('action'),

看起来您的表单来自您的manage_groups()函数,因此您的调用将在此函数内部进行。

试试这个 :

 url: "/upload/foto"

希望它会奏效

© www.soinside.com 2019 - 2024. All rights reserved.