如何根据ajax响应显示/隐藏div?

时间:2013-05-22 18:24:54

标签: jquery ajax grails

现在我有两个网络服务;一个是我的主应用程序,另一个是返回JSON数据。我试图根据作为对帖子的响应而获得的JSON数据中的值来显示/隐藏div。添加此逻辑的最佳方式/位置是什么/何处?这是我到目前为止的一些代码。 ajax调用工作正常,我能够根据响应呈现消息,但我不确定基于ajax响应显示/隐藏div的逻辑。感谢。

控制器动作:

def checkItemProperty() {
  def service = new MyService()
  def itemInstance = new Item(params)
  String itemProperty = itemInstance.itemProperty

  if (service.checkItemCondition(itemProperty)) {
    render "Property is true"
  }
  else {
    render "Property is false"
  }
}

gsp head snippet:

<g:javascript library="jquery" />
<g:javascript>
  $(document).ready(function() {
    $("#showHideDiv").hide();
    $("#someClickableLink").click(function(){ $("#showHideDiv").show(); });
  });
</g:javascript>

gsp body snippet:

<g:formRemote name="testForm" url="[action:'checkItemProperty']" update="[success: 'message', failure: 'error']">
  <g:textField name="itemProperty" value="${itemInstance?.itemProperty}" />
  <g:actionSubmit type="submit" name="add" value="Check" />
  <span id="message"></span>
  <span id="error"></span>
</g:formRemote>

<div id="showHideDiv">...</div>

修改 服务方式:

def checkItemCondition(String itemProperty) {
  def test = new RESTClient('http://localhost:8081/test/')
  def testResponse = test.post(path : 'test.json', body : [status:itemProperty, source:'httpbuilder'], requestContentType : URLENC)
  def jsonObject = testResponse.getData()
  return jsonObject['itemResponse']
}

修改 我如何构造上述控制器操作的JSON数据:

def test = [:]
test.value = true
test.text = 'Property is true'
render test as JSON

2 个答案:

答案 0 :(得分:5)

您必须更改控制器:

控制器:

render [value: true, text: "Property is true"] as JSON

render [value: false, text: "Property is false"] as JSON

GSP(删除update属性):

<g:formRemote ... onSuccess="handleResponse(data)">

JavaScript的:

function handleResponse(data) {
$("#message").html(data.text);
if (data.value) {
 $("#showHideDiv").show();
}
else {
 $("#showHideDiv").hide();
}
}

答案 1 :(得分:0)

如果没有看到您现有的帖子,我可以近似:

$.post(yoururl, yourdata, function(postresultdata){
     $("#showHideDiv").show();
});
相关问题