的getJSON JavaScript函数返回undefined对象

问题描述:

这是我的JavaScript代码:的getJSON JavaScript函数返回undefined对象

// action when item file is clicked 
$("li span.file").click(function(){ 

    // get the ID 
    console.log($(this).attr('id')); 

    $.getJSON('BomItemToJSON', function(data) { 
     $.each(data, function(i, item) { 
      var id = item.id; 
      var description = item.description; 

      formObject = document.forms['itemForm']; 
      formObject.elements['itemId'].value = id; 
      formObject.elements['itemDescription'].value = description; 
     }); 
    }); 

}); 

这是我的servlet的一部分:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

     utx.begin(); 

     BomHandling bh = new BomHandling(em, utx); 

     BomItem item = bh.getBomItem(63788); 
     Gson gson = new Gson(); 
     String json = gson.toJson(item); 

     System.out.println("Json: " + json); 

     response.setContentType("application/json"); 
     response.setCharacterEncoding("UTF-8"); 
     response.getWriter().write(json); 
     utx.commit(); 
    } 

它返回:

Json: {"itemId":63788,"modules":[],"deprecated":false,"partNumber":"SG-XPCIE8SAS-E-Z","description":"4 GB Memory Expansion (2 x 2GB) low-profile FBDIMMs, Gen 2, 1.8 V, for Sun SPARC Enterprise, RoHS 6. (For Factory Integration Only)","quantity":0,"unitPriceDollar":"$350.00","discount":"10%","totalDollar":"$0.00","itemClass":"Server","itemType":"HW","vendor":"Sun"} 

从控制台日志I知道这个servlet叫做:

[09:22:11.633] GET http://localhost:8084/xxx/BomItemToJSON [HTTP/1.1 200 OK 80ms] 

这是我形式

<div id="itemdetail"> 
    <form name="itemForm"> 
     ID: <input type="text" name="itemId" value="" size="100"></input> 
     Description: <input type="text" name="itemDescription" value="" size="100"></input> 
    </form> 
</div> 

我怎样才能插入的itemId,并从JSON对象描述成我的形式?现在它总是'未定义'。

你不需要每个。你的JSON只是一个单一的对象,而不是一个数组。

您的代码应该是这样的,我认为:

// action when item file is clicked 
$("li span.file").click(function(){ 

    // get the ID 
    console.log($(this).attr('id')); 

    $.getJSON('BomItemToJSON', function(data) { 
     alert('entered getJSON()'); 
     var id = data.itemId; 
     var description = data.description; 

     alert('description: ' + description); 

     formObject = document.forms['itemForm']; 
     formObject.elements['itemId'].value = id; 
     formObject.elements['itemDescription'].value = description; 

     alert('done with javascript'); 
    }); 

}); 

JSON对象应括号内包裹:{ Json: { ... } } 如果你试图用jsonLint来验证您的JSON你可以看到

+0

我认为错误关于这一点,不清楚OP是否说“这是我的Json:”或者这是代码的一部分。 – 2012-04-18 07:33:23

+0

:)在开始查看与JSON有关的代码时出现代码错误之前,我通常会仔细检查返回的结构 – fcalderan 2012-04-18 07:36:10

+0

看看他的servlet代码,它看起来像是这一行的输出:'System.out.println(“Json :“+ json);'这可能不是代码的一部分。 – 2012-04-18 07:37:31