簡體   English   中英

getJSON JavaScript函數返回未定義的對象

[英]getJSON JavaScript function returns undefined object

這是我的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');
    });

});

JSON對象應該放在方括號內: { Json: { ... } }如果嘗試使用jsonLint驗證json, 則會注意到錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM