gpt4 book ai didi

java - getJSON JavaScript 函数返回 undefined object

转载 作者:行者123 更新时间:2023-11-29 08:07:28 25 4
gpt4 key购买 nike

这是我的 JavaScript 代码:

// 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"}

从控制台日志我知道这个 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>

如何将 JSON 对象中的 itemId 和描述插入到我的表单中?现在它始终是“未定义的”。

最佳答案

您不需要每个。您的 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');
});

});

关于java - getJSON JavaScript 函数返回 undefined object ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10204837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com