Im 학습 젠드 프레임 워크 2. 젠드 모달 창 아약스 요청을 젠드에서 만드는 방법에 대한 게시물을 찾았습니다. 사용자가 앨범 이름과 앨범 유형을 추가 할 수있는 작은 팝업 창을 만들었습니다. 나는 아래의 스크립트를 실행할 때 Jquery 모달 창없이 내 데이터베이스에 완벽하게 저장되지만 아약스를 통해 데이터베이스에 들어갈 필요가 전혀 없다. 나는 오류 찾기 시작하고 난 형태로 게시 할 때 콘솔에서 발견 :젠드 프레임 워크 2 아약스 요청 오류
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
http://localhost/album/validatepostajax
을하지만 난 URL을 클릭있을 때 그것을로드합니다.
도움을 주시면 대단히 감사하겠습니다.
컨트롤러 :
<?php
namespace Album\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class AddNewAlbumController extends AbstractActionController {
public function savetodb($data)
{
$mapper = $this->getServiceLocator()->get('Album/Mapper/Album');
$mapper->insert($data);
}
protected function getForm()
{
$form = $this->getServiceLocator()->get('Album\Form\AddNewAlbumForm');
$form->setInputFilter(new \Album\Form\Filters\AddNewAlbumFormFilter());
$form->setName('AlbumForm');
return $form;
}
public function newalbumAction()
{
$viewmodel = new ViewModel();
$viewmodel->setTemplate('album/form/add-album.phtml');
$form = $this->getForm();
$form->setHydrator (new \Zend\Stdlib\Hydrator\Reflection());
$request = $this->getRequest();
//disable layout if request by Ajax
$viewmodel->setTerminal($request->isXmlHttpRequest());
$is_xmlhttprequest = 1;
if (! $request->isXmlHttpRequest()){
//if NOT using Ajax
$is_xmlhttprequest = 0;
if ($request->isPost()){
$form->bind (new \Album\Entity\Album());
$form->setData($request->getPost());
$mapper = $this->getServiceLocator()->get('Album/Mapper/Album');
if ($form->isValid()){
$this->savetodb($form->getData());
}
}
}
$viewmodel->setVariables(array(
'form' => $form,
'is_xmlhttprequest' => $is_xmlhttprequest //need for check this form is in modal dialog or not in view
));
return $viewmodel;
}
public function validatepostajaxAction()
{
$form = $this->getForm();
$form->setHydrator (new \Zend\Stdlib\Hydrator\Reflection());
$request = $this->getRequest();
$response = $this->getResponse();
$messages = array();
if ($request->isPost()){
$form->bind (new \Album\Entity\Album());
$form->setData($request->getPost());
if (! $form->isValid()) {
$errors = $form->getMessages();
foreach($errors as $key=>$row)
{
if (!empty($row) && $key != 'submit') {
foreach($row as $keyer => $rower)
{
$messages[$key][] = $rower;
}
}
}
}
if (!empty($messages)){
$response->setContent(\Zend\Json\Json::encode($messages));
} else {
$this->savetodb($form->getData());
$response->setContent(\Zend\Json\Json::encode(array('success'=>1)));
}
}
return $response;
}
}
보기 :
<script type="text/javascript">
var is_xmlhttprequest = <?php echo $this->is_xmlhttprequest; ?>;
var urlform = '<?php echo $this->url('album\newalbum',
array('action' => 'validatepostajax'));?>';
</script>
<?php echo $this->headScript()->appendFile($this->basePath() . '/js/ajaxform-up.js'); ?>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url('album\newalbum',
array('action' => 'newalbum'))
);
$form->prepare();
?>
<?php
echo $this->form()->openTag($form);
?>
<div class="element element_name">
<?php echo $this->formlabel($form->get('name')). $this->formelement($form->get('name'));?>
</div>
<div class="element element_type">
<?php echo $this->formElement($form->get('type'));?>
</div>
<?php echo $this->formElement($form->get('submit')).$this->form()->closeTag(); ?>
JS :
$(function(){
$("form#AlbumForm").submit(function(){
if (is_xmlhttprequest == 0)
return true;
$.post(urlform, { 'name' : $('input[name=name]').val(),
'type' : $('select[name=type]').val()}, function(itemJson){
var error = false;
if (itemJson.name != undefined){
$(".element_name").append("<div class = 'alert alert-error'>"+itemJson.name[0]+"</div>");
error = true;
}
if (itemJson.type != undefined){
$(".element_type").append("<div class = 'alert alert-error'>"+itemJson.type[0]+"</div>");
error = true;
}
$("winpopup").dialog("option", "position", { my: "center", at: "center", of: window });
if (!error){
$("#winpopup").dialog('close');
location.reload();
if (itemJson.success == 1){
alert('Data saved');
}
}
}, 'json');
return false;
});
});
1. 모듈 구성 파일에 이것을 추가 했습니까? 'strategies'=> array ( 'ViewJsonStrategy',),. 2. js가로드 중입니까? 3. 일부 코드 invalidatepostajaxAction()을 주석 처리하고 간단한 echo를 추가하고 exit(); 당신이 응답을 얻을 수 있는지보기 위해서 – dixromos98
@ dixromos98 도움을 주셔서 감사합니다.그래서 : 1) 그렇습니다. validatepostajaxAction()'$ this-> savetodb ($ form-> getData()); 부분 만 이제는'$ response-> setContent (\ Zend \ Json \ Json :: encode (array ('success'=> 1))); 실행 중입니다. 경고가 팝업되므로 데이터베이스에 저장할 수없는 이유를 실제로 알지 못합니다. – Wermerb
그래, Ajax가 작동한다는 것을 알았습니다. 당신이 반응을 얻었 기 때문에 (좋은 소식). 이제 로컬 호스트 로그를 검사하여 문제의 원인을 확인하거나 코드의 각 행이 예외의 원인을 확인하도록 테스트해야합니다. – dixromos98