liuyuanjiang109からの転送:https://blog.csdn.net/liuyuanjiang109/article/details/78972644
Ajaxは、参加に問題がある場合、RESTfulサービスを使用してPutおよびDeleteリクエストを直接送信します
1. POST + _method:delete / put + filterメソッド
Ajaxを使用してputおよびdeleteリクエストを送信する場合、パラメーターを渡す必要があります。パラメーターがURLアドレスバーにある場合は、通常どおり使用できます。
データでパラメーターを渡す必要がある場合(ブラウザーはフォーム送信方法を使用して送信します)、次の変更に注意する必要があります。
1.リクエストメソッドは次のように設定されています: "post"、
2. __method: "DELETE"または_method: "PUT"パラメーターをデータに追加します。
data:{_ method: "DELETE"、id:issueId、userId:userId}、
3。バックグラウンドコントローラーは引き続き対応するDELETEリクエストです
@RequestMapping(value = "/ answer / {answerId}"、method = RequestMethod.DELETE)
public ResponseResult deleteAnswer(@PathVariable( "answerId")int answerId、Issue issue){ //オブジェクトに自動的にカプセル化できる場合、直接使用できますオブジェクトパラメーター} 4。対応するフィルターを構成する必要があります(Spring Bootを使用すると自動的に構成されます)
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<!-- 备注,这边的名称必须和配置'springmvc'的servlet名称一样 -->
<servlet-name>springmvc</servlet-name>
</filter-mapping>
ajaxコードは次のとおりです。
var r=confirm("确认删除该?");
if(r){
$.ajax({
url:"http://localhost:8888/answer/"+answerId,
type:"POST",
data:{_method:"DELETE", id:issueId,userId:userId},
dataType:"json",
success:function(result){
}
},
});
PS:springbootを使用する場合は、ステップ4を省略できます。これは、springbootが開始すると、HiddenMethodFilter
2が読み込まれ、PUT DELETEリクエスト
が引き続き使用されるためです。1。PutおよびDeleteリクエストは引き続き使用され、パラメーターを渡す必要がある場合は、データはjson文字列に設定する必要があります
var jsonstr = {"id":issueId,"userId":userId};
var r=confirm("确认删除该回答?");
if(r){
$.ajax({
url:"http://localhost:8885/answer/"+answerId,
type:"DELETE",
contentType:"application/json",//设置请求参数类型为json字符串
data:JSON.stringify(jsonstr),//将json对象转换成json字符串发送
dataType:"json",
success:function(result){
},
});
}
クライアントは@RequestBodyアノテーションを使用する必要があります
@RequestMapping(value="/answer/{answerId}",method=RequestMethod.DELETE)
public ResponseResult deleteAnswer(@PathVariable("answerId")int answerId,@RequestBody Issue issue){
}
最後に、フロントエンドがリクエストヘッダーフィールドContent-Typeがプリフライト応答でAccess-Control-Allow-Headersによって許可されていないことを促すエラーを報告した場合は、次の解決策を参照できます。
https://stackoverflow.com/questions/12409600/error-request-header-field-content-type-is-not-allowed-by-access-control-allow
フィルタを書くことができます
@WebFilter(servletNames={"dispatcherServlet"})//可配置对应的请求servlet 此处使用 springMVC
public class AjaxFilter implements Filter{
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse httpServletResponse=(HttpServletResponse) response;
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Allow-Methods","GET,POST,DELETE,PUT");
httpServletResponse.setHeader("Access-Control-Allow-Headers","Origin,X-Requested-With,Content-Type,Accept");
chain.doFilter(request, response);
}
}