Php 使用Ajax将表单数据发布到ZF2控制器
编辑-Php 使用Ajax将表单数据发布到ZF2控制器,php,ajax,controller,xmlhttprequest,zend-framework2,Php,Ajax,Controller,Xmlhttprequest,Zend Framework2,编辑- 我已经在下面发布了答案。 问题是,当按下提交按钮时,我不理解ZF2如何/在何处发布表单数据。因此,如果($this->getRequest()->isPost()){ 在下面的ajax调用之后,它告诉我没有发布任何数据。 当我执行上面的isPost()if语句时,当我点击提交按钮,告诉我数据已经发布,然后告诉我表单数据 这是有效的 这里是ajax调用- <script> $.ajax({
我已经在下面发布了答案。 问题是,当按下提交按钮时,我不理解ZF2如何/在何处发布表单数据。因此,如果($this->getRequest()->isPost()){
在下面的ajax调用之后,它告诉我没有发布任何数据。
当我执行上面的
isPost()
if语句时,当我点击提交按钮,告诉我数据已经发布,然后告诉我表单数据
这是有效的
这里是ajax调用-
<script>
$.ajax({
url: urlform,
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: true,
data: ($("#newThoughtForm").serialize() + '&submit=go'),
success: function () {
console.log('SUBMIT WORKS');
setTimeout(function () { <?php echo $this->invokeIndexAction()->test(); ?> ;
}, 1000);
},
//This keeps getting executed because there is no response, as the controller action is not run on a Post()
error: function () {
console.log('There is error while submit');
setTimeout(function () { <?php echo $this->invokeIndexAction()->test(); ?> ;
}, 1000);
}
//I assume the data won't get pushed to the server if there is no response,
//but I can't figure out how to give a response in ZF2 since the controller is not
//run when the Post() is made.
});
Request URL:http://test/newAlbum.html
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:46
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:PHPSESSID=h46r1fmj35d1vu11nua3r49he4
Host:test
Origin:http://test
Referer:http://test/newAlbum.html
User-Agent:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
album[albumText]:hello world
submit:go
Response Headersview source
Connection:Keep-Alive
Content-Length:4139
Content-Type:text/html
Date:Sun, 20 Oct 2013 16:52:15 GMT
Keep-Alive:timeout=5, max=99
Server:Apache/2.4.4 (Win64) PHP/5.4.12
X-Powered-By:PHP/5.4.12
对ajax调用的请求-
<script>
$.ajax({
url: urlform,
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: true,
data: ($("#newThoughtForm").serialize() + '&submit=go'),
success: function () {
console.log('SUBMIT WORKS');
setTimeout(function () { <?php echo $this->invokeIndexAction()->test(); ?> ;
}, 1000);
},
//This keeps getting executed because there is no response, as the controller action is not run on a Post()
error: function () {
console.log('There is error while submit');
setTimeout(function () { <?php echo $this->invokeIndexAction()->test(); ?> ;
}, 1000);
}
//I assume the data won't get pushed to the server if there is no response,
//but I can't figure out how to give a response in ZF2 since the controller is not
//run when the Post() is made.
});
Request URL:http://test/newAlbum.html
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:46
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:PHPSESSID=h46r1fmj35d1vu11nua3r49he4
Host:test
Origin:http://test
Referer:http://test/newAlbum.html
User-Agent:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
album[albumText]:hello world
submit:go
Response Headersview source
Connection:Keep-Alive
Content-Length:4139
Content-Type:text/html
Date:Sun, 20 Oct 2013 16:52:15 GMT
Keep-Alive:timeout=5, max=99
Server:Apache/2.4.4 (Win64) PHP/5.4.12
X-Powered-By:PHP/5.4.12
“提交”按钮的请求-
Request URL:http://test/newAlbum.html
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:46
Content-Type:application/x-www-form-urlencoded
Cookie:PHPSESSID=h46r1fmj35d1vu11nua3r49he4
Host:test
Origin:http://test
Referer:http://test/newAlbum.html
User-Agent:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
Form Dataview sourceview URL encoded
album[albumText]:hello world
submit:go
Response Headersview source
Connection:Keep-Alive
Content-Length:4139
Content-Type:text/html
Date:Sun, 20 Oct 2013 16:52:14 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.4 (Win64) PHP/5.4.12
X-Powered-By:PHP/5.4.12
以下是控制器上的indexAction(),以确保完整性-
public function indexAction()
{
echo 'console.log("Index Action is Called");';
$form = new \AlbumModule\Form\newAlbumForm();
if ($this->getRequest()->isPost()){
echo 'console.log("Data posted");';
$form->setData($this->getRequest()->getPost());
if ($form->isValid()){
echo 'console.log("Form Valid");';
//todo
$this->forward()->dispatch('newAlbum', array('action' => 'submitAlbum'));
return new ViewModel(
array(
'form' => $form
)
);
} else {
echo 'console.log("Form Invalid");';
return new ViewModel(
array(
'form' => $form
)
);
}
} else {
echo 'console.log("No data posted")';
return new ViewModel(
array(
'form' => $form
)
);
}
}
正如我在开头所说的,当按钮提交表单时,isPost()
类将返回值true,但当表单通过Ajax提交时,它将返回值false
编辑-
我已经在下面发布了答案。通常,当您从ajax发送数据时,不需要再次呈现模板,而ViewModel就是这样做的 尝试将json策略添加到module.config.php中
'view_manager' => array(
//other configuration
'strategies' => array(
'ViewJsonStrategy',
),
),
return [
'view_manager'=>[
'Strategies'=> 'ViewJsonStrategy',
]
]
那么您的操作应该如下所示:
public function ajaxAction()
{
$request = $this->getRequest();
if ($request->isXmlHttpRequest()){ // If it's ajax call
$data = $request->getPost('data'));
...
}
return new JsonModel($formData);
}
多亏了SzymonM我才弄明白 基本上,您似乎必须以json类型发布到操作,这意味着您发布到的任何控制器/操作都必须为jQueryAjax调用返回“成功”响应,才能返回成功。
因此,尝试发布到索引操作会产生问题,因为您可能试图通过许多if语句返回viewModel对象或json响应。
最好的选择是将json请求发布到另一个操作,该操作将管理请求和响应 Ajax操作-
public function ajaxAction()
{
$form = new \AlbumModule\Form\newAlbumForm();
$request = $this->getRequest();
$response = $this->getResponse();
if ($request->isPost()) {
//$hello is a test variable used for checking if the form is valid
//by checking the response
$hello = 1;
$form->setData($request->getPost());
if ($form->isValid()){
$hello = 4020;
};
}
$messages = array();
if (!empty($messages)){
$response->setContent(\Zend\Json\Json::encode($messages));
} else {
$response->setContent(\Zend\Json\Json::encode(array('success'=>1,'hello'=>$hello)));
}
return $response;
}
Ajax调用-
var urlform='';
$.ajax({
url:urlform,
键入:“POST”,
数据类型:“json”,
async:true,
数据:$(“#newAlbumForm”).serialize(),
成功:功能(数据){
控制台日志(数据);
}
错误:函数(数据){
控制台日志(数据);
}
});
最好的方法是使用
可接受的视图模型选择器
控制器插件,用于在不同策略之间切换
module.config.php中的第一个
'view_manager' => array(
//other configuration
'strategies' => array(
'ViewJsonStrategy',
),
),
return [
'view_manager'=>[
'Strategies'=> 'ViewJsonStrategy',
]
]
在控制器示例中:indexAction中的IndexController.php
class IndexController extends AbstarctActionController{
protected $accptCretiria = [
'Zend\View\Model\ViewModel'=>'text/html',
'Zend\View\Model\JsonModel'=>'application/json, text/json'
];
public function indexAction(){
//here if is ajax call it returns jsonView ,and if is normal call it return ViewModel
$viewModel = $this->acceptableViewModelSelector($this->acceptCretiria);
return $viewModel
}
}
Zend Framework 2有一个名为WasabiLib的模块。它几乎拥有所有功能,可以以非常方便的方式管理ajax请求和响应。请看一个简单的示例,它提供了一个简单的表单:
//inside the phtml
<form id="simpleForm" class="ajax_element" action="simpleFormExample" method="POST"
data-ajax-loader="myLoader">
<input type="text" name="written_text">
<input type="submit" value="try it">
<i id="myLoader" class="fa fa-spinner fa-pulse fa-lg" style="display: none;"></i>
</form>
//Server-side code
public function simpleFormExampleAction(){
$postArray = $this->getRequest()->getPost();
$input = $postArray['written_text'];
$response = new Response(new InnerHtml("#element_simple_form","Server Response: ".$input));
return $this->getResponse()->setContent($response);
}
//在phtml内部
//服务器端代码
公共函数simpleFormExampleAction(){
$postArray=$this->getRequest()->getPost();
$input=$postArray['writed_text'];
$response=newresponse(新的InnerHtml(“#元素_简单_形式”,“服务器响应:”.$input));
返回$this->getResponse()->setContent($response);
}
在进行一些测试之后,似乎$this->getRequest
没有以Post或XmlHttpRequest的形式返回。我不确定为什么在ajax调用中数据没有传递到服务器:(.我甚至尝试将ajax调用url更改为”;
,但似乎没有任何效果。我发现我必须使用$data=$request->getPost()->toArray();
来获取控制器中的传入数据。