2013-11-26 112 views
3

我是ajax的新手。我正在尝试从我的gsp页面向控制器操作发送请求。但我失败了。它不调用控制器操作,页面正在重新加载。任何人都可以看看这个和帮助。这是我的看法波纹管页面>>>从gsp页面在grails中调用ajax调用

<%@ page contentType="text/html;charset=UTF-8" %> 
<html> 
<head> 
    <title>Ajax First Example</title> 
    <g:javascript plugin="jquery" library="jquery" src="jquery/jquery-1.7.2.js"/> 
    <script> 
     function callAjax(){ 
      $.ajax({ 
       url: "returnMe", 
       type:"post", 
       dataType: 'json', 
//   data:{ids:JSON.stringify(idList), option:option, id:id} 
       success: function() { 
        alert(1) 
       } 
      }); 
     } 
    </script> 
</head> 
<body> 
<form name='myForm'> 
    <input type="submit" value="Call Ajax Function" onclick="callAjax()"> 
</form> 
</body> 
</html> 

这里是我的控制器操作>>>

def returnMe = { 
    String msg = 'sdfsdf' 
    render msg as JSON 
} 

回答

6

你可以试试这个:

onclick="callAjax() return false;"> 

或者这一个:

function callAjax(e){ //<-------pass the event 
     e.preventDefault(); // <-----add this to prevent the default behavior 
     $.ajax({ 
      ..... 
     }); 
} 

您的完整阿贾克斯呼叫请求:

function callAjax(){ 
     $.ajax({ 
      url: "returnMe", 
      type:"post", 
      dataType: 'json', 
//   data:{ids:JSON.stringify(idList), option:option, id:id} 
      success: function(data) { 
       console.log(data); //<-----this logs the data in browser's console 
      }, 
      error: function(xhr){ 
       alert(xhr.responseText); //<----when no data alert the err msg 
      } 
     }); 
    } 
+0

感谢您的帮助。第一个为我工作。但它并没有警惕成功。只有管​​制员的行动正在被召唤。我现在该怎么办? –

+0

你可以尝试向你的ajax添加错误函数,并且看看你的控制器是否正确生成'“json”'。 – Jai

+0

是的,我的JSON没有正确构建。现在我已将其更改为html。现在没事了。但是,请您给我一个完整的ajax调用结构的链接。谢谢。 –