JSON object parsing error using jQuery Form Plugin

2019-07-12 20:06发布

问题:

Environment: JQuery Form Plugin, jQuery 1.7.1, Zend Framework 1.11.11.

Cannot figure out why jQuery won't parse my json object if I specify an url other than a php file. The form is as follows:

<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>

The javascript triggering the ajax request is:

<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>

The code in my zend controller is:

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"));
}

}

When I create an upload.php file with the above code, and modify the url from the ajax request to

url: "upload.php",

i don't run into that parsing error, and the json object is properly returned. Any help to figure out what I'm doing wrong would be greatly appreciated! Thanks.

回答1:

You need either to disable layouts, or using an action helper such as ContextSwitch or AjaxContext (even better).

First option:

$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout->disableLayout();

And for the second option, using AjaxContext, you should add in your _init() method:

$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('upload', 'json')
            ->initContext();

This will disable automatically disable layouts and send a json header response.

So, instead of your two json_encode lines, you should write:

$this->status = "success";
$this->message = "posted successfully";

and

$this->status = "fail";
$this->message = "not posted successfully";

In order to set what to send back to the client, you simply have to assign whatever content you want into view variables, and these variables will be automatically convert to json (through Zend_Json).

Also, in order to tell your controller which action should be triggered, you need to add /format/json at the end of your URL in your jQuery script as follow:

url: "<?php $this->baseURL();?>/contact/upload/format/json",

More information about AjaxContext in the manual.



回答2:

Is the Content-type header being properly set as "application/json" when returning your JSON?