jQuery Ajax 无法将 PUT 和 DELETE REST API 发送到 ZF2 服务器

jQuery Ajax unable to send PUT and DELETE REST API to ZF2 server

我在从前端向 ZF2 后端发送 PUTDELETE REST API 时遇到问题。但是:我可以发送 POSTGET 请求并且工作正常,但 PUTDELETE 不会。为什么?

下面是我的 ajax 代码:

 $.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);
        }
    });

我从 ZF2 得到的错误是:

Zend\View\Renderer\PhpRenderer::render: Unable to render template "api/product/replace-list"; resolver could not resolve to a file

确保您将 restful 控制器与 JsonModel 一起使用。 restful 控制器将处理 restful 请求 PUTDELETEJsonModel 将产生 JSON 输出。

这是一个可能对您有所帮助的示例代码,

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

同样在 restful PUT 方法中需要两个参数

  1. ID(包含在url中)
  2. 数据(数组)

因此将您的 ajax 调用修改为

$.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);
    }
});