简体   繁体   English

如何使用jQuery处理JSON响应

[英]How to handle a JSON response with jQuery

I am able to send data to the server using JSON and get back the appropriate data, but before I handle the returned data appropriately I am just trying to output the returned JSON data as an alert. 我能够使用JSON将数据发送到服务器并获取适当的数据,但是在适当地处理返回的数据之前,我只是试图将返回的JSON数据作为警报输出。 I cannot understand why this is not working. 我不明白为什么这行不通。

I do get an alert but the text value says "undefined" - I am not sure what I need to do to either have it print the entire JSON object or one part of it. 我确实收到警报,但文本值显示为“未定义”-我不确定我需要做什么才能使其打印整个JSON对象或其中的一部分。

Both System.out.println statements confirm that the correct information is coming out of the servlet. 两个System.out.println语句都确认从servlet中发出了正确的信息。

The servlet class: Servlet类:

public class EditItemServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

    response.setContentType("text/json");
    PrintWriter out = response.getWriter();
    String itemToEdit = request.getParameter("selectedItem");

    System.out.println(itemToEdit);

    String myString="";
    try {
        myString = new JSONObject().put("selectedItem", itemToEdit).toString();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println(myString);
    out.print(myString);
    }
}

Here is the jQuery that sends the request and handles the response: 这是发送请求并处理响应的jQuery:

$("#edit-form").hide();
    $("#edit-item-btn").click(function () {
        isEditClicked = "yes";
        $("#edit-form").show();
        var editValue = $("#edit-item-select").val();
        $.getJSON("EditItem", {"selectedItem" : editValue}, displayEditValues());
        alert("wassup");
    }); 

    function displayEditValues(data) {
        alert(data);
    };  // each

您需要将displayEditValues作为回调传递,而不是调用displayEditValues()

$.getJSON("EditItem", {"selectedItem" : editValue}, displayEditValues);
$.getJSON("EditItem",{"selectedItem":editValue},function(){displayEditValues()});

这样,您可以将任意数量的参数传递给displayEditValues()函数,例如

function(){displayEditValues(param1, param2, ..., paramN)}

Try this: 尝试这个:

  displayEditValues = function(data) {
      alert(data);
  };
  $.getJSON("EditItem", {"selectedItem" : editValue}, displayEditValues);

Or even 甚至

  $.getJSON("EditItem", {"selectedItem" : editValue}, function(data) { alert(data); } );

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

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