问题描述:

I am having problem sending PUT and DELETE REST API from my front end to my ZF2 backend. However: I am able to send POST and GET request and it's working fine but not PUT and DELETE won't. Why?

Below is my ajax code:

 $.ajax({

type: "PUT",

dataType: "json",

data: data,

url: "/backend/api/product",

statusCode: {

200: function (data) {

product= data.content;

}

}, error: function (data) {

alert(data.responseJSON.message);

}

});

The error that I get from my ZF2 are:

Zend\View\Renderer\PhpRenderer::render: Unable to render template

"api/product/replace-list"; resolver could not resolve to a file

网友答案:

Make sure you are using restful controller with JsonModel. The restful controller will handle the restful requests PUT and DELETE. And the JsonModel will produce JSON output.

Here is a sample code that may help you,

use Zend\ViewModel\JsonModel;
use Zend\Mvc\Controller\AbstractRestfulController;

class ProductController extends AbstractRestfulController
{    
    public function delete($id){

        // to handle delete 
        $responseData = new JsonModel(array(
            'key' => 'value'            
        ));

        return $responseData ;
    }

    public function update($id, $data){

        // to handle update
        $responseData = new JsonModel(array(
            'key' => 'value'            
        ));

        return $responseData ;
    }
}

Also in restful PUT method requires two params

  1. ID (includes in url)
  2. DATA (array)

so modify your ajax call as

$.ajax({
    type: "PUT",
    dataType: "json",
    data: data,
    url: "/backend/api/product/"+id,
    statusCode: {
        200: function (data) {
            product= data.content;
        }
    }, error: function (data) {
        alert(data.responseJSON.message);
    }
});
网友答案:

Make sure you are using JsonModel, otherwise ZF2 will try to render the relevant phtml file

use Zend\ViewModel\JsonModel;
class IndexController extends ActionController
{
    public function indexAction()
    {

        $responseData = new JsonModel(array(
            'key' => 'value'            
        ));

        return $responseData ;
    }
}
相关阅读:
Top