开发者

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. 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.

Both System.out.println statements confirm that the correct information is coming out of the servlet.

The servlet class:

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);
    ou开发者_JS百科t.print(myString);
    }
}

Here is the jQuery that sends the request and handles the response:

$("#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


You need to pass the displayEditValues as a callback not invoke it displayEditValues():

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


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

By this way you can pass any number of parameters to your displayEditValues() function like

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); } );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜