环境:JQuery 表单插件、jQuery 1.7.1、Zend Framework 1.11.11。
无法弄清楚为什么如果我指定 php 文件以外的 url,jQuery 不会解析我的 json 对象。 形式如下:
<form id="imageform" enctype="multipart/form-data">
Upload your image <input type="file" name="photoimg" id="photoimg" />
<input type="submit" id ="button" value="Send" />
</form>
触发ajax请求的javascript是:
<script type="text/javascript" >
$(document).ready(function() {
var options = {
type: "POST",
url: "<?php $this->baseURL();?>/contact/upload",
dataType: 'json',
success: function(result) {
console.log(result);
},
error: function(ob,errStr) {
console.log(ob);
alert('There was an error processing your request. Please try again. '+errStr);
}
};
$("#imageform").ajaxForm(options);
});
</script>
我的 zend Controller 中的代码是:
class ContactController extends BaseController {
public function init() {
/* Initialize action controller here */
}
public function indexAction() {
}
public function uploadAction() {
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$image = $_FILES['photoimg']['tmp_name'];
$im = new imagick($image);
$im->pingImage($image);
$im->readImage($image);
$im->thumbnailImage(75, null);
$im->writeImage('userImages/test/test_thumb.jpg');
$im->destroy();
echo json_encode(array("status" => "success", "message" => "posted successfully"));
}
else
echo json_encode(array("status" => "fail", "message" => "not posted successfully"));
}
}
当我使用上面的代码创建upload.php文件,并将ajax请求中的url修改为
url: "upload.php",
我没有遇到解析错误,并且 json 对象已正确返回。任何帮助找出我做错了什么的帮助将不胜感激!谢谢。
最佳答案
您需要禁用布局,或者使用操作助手,例如 ContextSwitch 或 AjaxContext(更好)。
第一个选项:
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout->disableLayout();
对于第二个选项,使用 AjaxContext,您应该在 _init()
方法中添加:
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('upload', 'json')
->initContext();
这将禁用自动禁用布局并发送 json header 响应。
因此,您应该编写以下内容,而不是两行 json_encode
行:
$this->status = "success";
$this->message = "posted successfully";
和
$this->status = "fail";
$this->message = "not posted successfully";
为了设置发送回客户端的内容,您只需将想要的任何内容分配给 View 变量,这些变量将自动转换为 json(通过 Zend_Json)。
此外,为了告诉 Controller 应该触发哪个操作,您需要在 jQuery 脚本中的 URL 末尾添加 /format/json
,如下所示:
url: "<?php $this->baseURL();?>/contact/upload/format/json",
有关AjaxContext in the manual的更多信息.
关于zend-framework - 使用 jQuery Form Plugin 解析 JSON 对象时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9833555/