0

I am in newbie in JavaScript, JQuery and Ajax coding. I am using JQuery $.ajax method to invoke asyn REST call. Somehow I am not able to receive HTTP response JSON data.

I can see the below alert result. alert(data) method result is [Object Object] alert(data.toSource()) method result is ({"key1","value1"}) alert($.parseJSON(data)) method result is nothing

I have tested the below code in both firefox and chrome browsers.

<html>
<head>
<title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"</script>
</head>
<body>
    <form id="foo">
        <label for="bar">A bar</label>
        <input id="bar" name="bar" type="text" value="" />
        <input type="submit" value="Send" />
    </form>
    <!-- the result of the search will be rendered inside this div -->
    <div id="result"></div>
    <script>
        $("#foo").submit(function(event) {
            event.preventDefault();
            $("#result").html('');
            var values = $(this).serialize();
            $.ajax({
                url: "resources/helloWorld",
                type: "GET",
                dataType: 'json',
                success: function(data){
                    alert(data);
                    alert(data.toSource());
                    var r = $.parseJSON(data);
                    alert(r);
                    $("#result").html(data);
                },
                error:function(){
                    $("#result").html('there is error while submit');
                }  
            });
        });
    </script>
</body>

R H
  • 387
  • 3
  • 13

1 Answers1

2

From your post:

alert(data) -> [Object Object]

Right, alert() uses the string representation of the argument, and data is an object.

alert(data.toSource()) -> ({"key1","value1"})

Right, toSource() is a Gecko method that works as JSON.stringify.

alert($.parseJSON(data)) method result is nothing

Right, you are trying to parse an object.


What you want to do is something like perhaps:

success: function(data){
  $("#result").html(data.key1);
}
moonwave99
  • 21,957
  • 3
  • 43
  • 64
  • Thanks for helping me. Yes it works for me. I want to receive the entire JSON response and parse this JSON. because my JSON is very complex. Can't I use $.parseJSON method to parse my HTTP response ? – R H Jun 01 '13 at 21:06
  • @RaviHingarajiya your json is already parsed. Run a `console.log(data)` inside the `success` function in order to inspect it. – moonwave99 Jun 01 '13 at 21:25