简体   繁体   English

在Grails中将JSON对象呈现为AJAX调用

[英]Rendering JSON object to AJAX calls in grails

I am trying to auto-populate employee details on entering employee number. 我正在尝试在输入员工编号时自动填充员工详细信息。

In the controller I am calling a method that returns JSON object: 在控制器中,我正在调用一个返回JSON对象的方法:

    Gson gson = new Gson();
    System.out.println(gson.toJson(objEmp));
    return gson.toJson(objEmp);

In the controller I am returning to AJAX call as: 在控制器中,我以以下方式返回AJAX调用:

render(contentType: "application/json") {[data]}

AJAX call is as follows: AJAX调用如下:

$(document).keypress(function(e) {
if(e.which == 13){
    var URL="${createLink(controller:'employeeAdd',action:'getDetails')}";
    var empNo = $("#empNo").val(); 
    alert("empNo: " + empNo);
    $.ajax({
        type: "GET",
        url:URL,
        contentType: "application/json; charset=utf-8",            
        dataType: "json",
        data: {
            empNo:empNo
        },
           success: function (data) {

              $("#empNo").val(data.employeeNumber);
              $("#employeeName").val(data.employeeName);
           },
           error: function (jqXHR, exception) {
               var msg = '';
               if (jqXHR.status === 0) {
                   msg = 'Not connect.\n Verify Network.';
               } else if (jqXHR.status == 404) {
                   msg = 'Requested page not found. [404]';
               } else if (jqXHR.status == 500) {
                   msg = 'Internal Server Error [500].';
               } else if (exception === 'parsererror') {
                   msg = 'Requested JSON parse failed.';
               } else if (exception === 'timeout') {
                   msg = 'Time out error.';
               } else if (exception === 'abort') {
                   msg = 'Ajax request aborted.';
               } else {
                   msg = 'Uncaught Error.\n' + jqXHR.responseText;
               }

           },     
    });
};
});

I am not getting any error. 我没有任何错误。 Also nothing is auto populated even though data is present in JSON format. 即使数据以JSON格式存在,也不会自动填充任何内容。 I am new to JSON and AJAX calls. 我是JSON和AJAX调用的新手。 I tried codes from internet still I couldn't get the desired output. 我仍然尝试从互联网上获取代码,但仍无法获得所需的输出。 I am unable to find the error. 我找不到错误。 Any pointers will be of great help. 任何指针都会有很大帮助。 Thank you. 谢谢。

I made the following changes and the code worked: 我进行了以下更改,代码起作用了:

  1. Returned employee object from method. 从方法返回的员工对象。
  2. Rendered the object as JSON ==> render dataEmp as JSON 将对象呈现为JSON ==> render dataEmp as JSON
  3. Extracted data in AJAX call funtion ==> success: function (dataEmp) 在AJAX调用函数中提取的数据==>成功:函数(dataEmp)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM