使用 ajax 发布表单时获得 html 作为响应
Getting html as response when posting form using ajax
我的错误应该很容易被更有经验的开发人员发现,所以希望您能帮助我。
我在控制器方法中创建了一个表单:
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 returns 页面在普通 html 中成功,但是控制器方法没有被调用(断点没有命中)
根据要求
这是 tcp 包响应的屏幕截图
我错过了什么?
我不确定,但看起来你的 ajax 调用转到了你的函数 manage_groups()
。
在您的 ajax 通话中:
url: $(this).attr('action'),
看起来你的表单来自你的 manage_groups() 函数,所以你的调用进入了这个函数。
试试这个:
url: "/upload/foto"
希望有用
我的错误应该很容易被更有经验的开发人员发现,所以希望您能帮助我。
我在控制器方法中创建了一个表单:
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 returns 页面在普通 html 中成功,但是控制器方法没有被调用(断点没有命中)
根据要求
这是 tcp 包响应的屏幕截图
我错过了什么?
我不确定,但看起来你的 ajax 调用转到了你的函数 manage_groups()
。
在您的 ajax 通话中:
url: $(this).attr('action'),
看起来你的表单来自你的 manage_groups() 函数,所以你的调用进入了这个函数。
试试这个:
url: "/upload/foto"
希望有用