我的表单在这里,与Grails应用程序无关。
<g:form url="[resource:myClass, action:'update']" method="PUT" >
<fieldset class="form">
<g:render template="form"/>
</fieldset>
<fieldset class="buttons">
<g:actionSubmit action="update" value="update" />
</fieldset>
</g:form>
如果我定期提交,一切正常。但是如果我尝试使用我的restfulcontroller,我会收到一条成功的保存消息,但它从不保存任何内容。
import grails.rest.RestfulController
import grails.transaction.Transactional
class MyClassRestController extends RestfulController<MyClass> {
static allowedMethods = [update: "PUT"]
@SuppressWarnings("GroovyUnusedDeclaration")
static responseFormats = ['json', 'xml']
@Transactional
def update(MyClass myClassInstance) {
myClassInstance.save flush:true, failOnError: true
respond new Expando(success: true, message: 'updated', myClass: myClassInstance)
}
}
这看起来很简单,这就是我提交的方式:
<script type="text/javascript">
$(function () {
var frm = $('form');
frm.on('submit', function (e) {
e.preventDefault();
$.ajax({
type: "PUT",
url: putUrl,
data: JSON.stringify(frm.serializeArray()),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.info(data);
},
failure: function (errMsg) {
console.info(errMsg)
}
});
});
});
</script>
在控制台中看起来一切都是正确的,我得到了我的成功消息和MyClassInstance,但它是未经编辑的MyClass - 就好像是通过GORM查找并忽略了我的PUT发送的内容。我忘记了什么?我是否必须为PUT设置“保持”和myClassInstance?
以下是我的要求:
忽略创建的日期部分,它会被覆盖。以下是回复:
{
"metaPropertyValues": [
{
"class":"groovy.lang.MetaExpandoProperty",
"modifiers":1,
"name":"success",
"type":"java.lang.Object"
},
{
"class":"groovy.lang.MetaExpandoProperty",
"modifiers":1,
"name":"message",
"type":"java.lang.Object"
},
{
"class":"groovy.lang.MetaExpandoProperty",
"modifiers":1,
"name":"auctionUser",
"type":"java.lang.Object"
}
],
"properties":{
"success":true,
"message":"AuctionUser updated",
"auctionUser":{
"class":"Auction.AuctionUser",
"id":2,
"addressCity":"Minneapolis",
"addressState":"MN",
"addressStreet":"1234 ABC Street",
"addressZip":"55408",
"created":"2015-03-31T05:00:00Z",
"firstName":"Trat",
"lastName":"Tauer",
"username":"trat@naspinski.net"
}
}
}
您可以忽略其中的大部分内容,但请注意,addressStreet和firstName将作为先前的值返回,而不是作为通过PUT传递的JSON。这有什么不对?
答案 0 :(得分:0)
您正在使用HTTP方法=“ PUT”创建表单,该表单无效,最终会using the default method GET
Grails要做的是使用POST参数来建立HTTP方法的隧道
<g:form method="post" class="form-horizontal" role="form" >
<g:hiddenField name="_method" value="PUT" />
尝试一下
<g:form url="[resource:myClass, action:'update']" method="POST" >
<g:hiddenField name="_method" value="PUT" />
<fieldset class="form">
<g:render template="form"/>
</fieldset>
<fieldset class="buttons">
<g:actionSubmit action="update" value="update" />
</fieldset>
</g:form>