JSON Post not working with jQuery Ajax call, works when I use Curl
出于某种原因,我的jQuery ajax请求无效。 每次我点击调用以下javascript的按钮时,POST都不成功,我收到错误:
1 | {"status":"KO","message":"error"} (see my controller action method). |
如果我使用curl,它工作正常,我得到响应"它工作!":
1 | curl --include --request POST --header"Content-type: application/json" --data '{"articleId":28,"isApproved": true}' http://localhost:9000/article/changeStatus |
我似乎正在做正确的事情,我在json部分字符串,设置内容类型,这里可能有什么问题?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var d = JSON.stringify({"articleId": articleId,"isApproved": isApproved}); $.ajax({ "type":"POST", "url":"/article/changeStatus", "data": d, "dataType":"json", "contentType":"application/json;charset=utf-8", "success": function(p) { alert('success is ' + p.isSuccess + ' message=' + p.message); }, "error": function(p) { }, "complete": function(p){ } }); |
我的控制器动作如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | def changeStatus = Action(BodyParsers.parse.json) { request => val changeStatusRequest = request.body.validate[ChangeStatusRequest] changeStatusRequest.fold( errors => { BadRequest(Json.obj("status" ->"KO","message" ->"error")) }, cmRequest => { Ok("it works!") } ) } case class ChangeStatusRequest(articleId: Int, isApproved: Boolean) |
读数是:
1 2 3 4 | implicit val changeStatusRequest: Reads[ChangeStatusRequest] = ( (JsPath "articleId").read[Int] and (JsPath "isApproved").read[Boolean] )(ChangeStatusRequest.apply _) |
有趣。 这对我来说并不是很明显。 我在您的控制器中尝试
"))
事实证明,
这些SO问题更详细:
- Jquery ajax错误回调
- Ajax请求返回200 OK,但是触发了错误事件而不是成功
我不太了解所以我无法解释为什么这应该有用,但让我们试一试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var d = JSON.stringify({"articleId": articleId,"isApproved": isApproved}); $.ajax({ type:"POST", url:"/article/changeStatus", data: d, contentType:"application/json;charset=utf-8", success: function(p) { alert('success is ' + p.isSuccess + ' message=' + p.message); }, error: function(p) { }, complete: function(p){ } }); |