开发者

Json object display

开发者 https://www.devze.com 2023-02-22 09:26 出处:网络
I am getting a json result like this after making an ajax call {\"answer\":{\"isPresent\":true,\"test\":{\"string\":[\"\"]},\"Id\":310}}

I am getting a json result like this after making an ajax call

{"answer":{"isPresent":true,"test":{"string":[""]},"Id":310}}

i want the contents of test in an text area. When i retrieve and display the contents of "test" in a text area i am getting only this

[Object object]

how to serialize this value?

Code:

$.ajax(
        {
                async:      true,
                beforeSend: function(){

                            },
                url:        'beginDisplay.do',
                type:       'POST',
                data:       param,
                dataType:   'json',
                success:    function(data, textStatus, XMLHttpRequest){ 

                                var isPresent= data.answer.isPresent;
                                if(isPresent){

                                var testString = data.answer.test;
                                $("#textArea").val(testString);


                            },
                error  :    function(XMLHttpRequest, textStatus, errorThrown){
                                //alert(XMLHttpRequest.responseText+" http code"+XMLHttpRequest.statusCode);
                                //alert('XMLHttpRequest:'+XMLHttpReq开发者_如何学JAVAuest+'===>> textStatus:'+textStatus+'==>>errorThrown:'+errorThrown);
                            },
                complete :  function(){
                                //alert('after complete....');
                                //unblockUI();
                            }
        }
    );


This is how I test in javascript console:

var j = {"answer":{"isPresent":true,"test":{"string":["text you want"]},"Id":310}};
console.log(j.answer.test.string)
>> ["text you want"]

In the result above, j.answer.test.string is still an object, therefore you need to specify the node value you want.

So, in your code, you may do this:

var testString = data.answer.test.string[0];
$("#textArea").val(testString);

However, I suggest you not to use "string" as your variable id. Use something like "str" instead.

Gory details: http://json.org/js.html


you'll want to use the JSON.stringify method, provided by the JSON2 library, and natively by most browsers (except IE<=7) if you want a JSON serialized version of the data in the text area.


Right now, the data inside test is an object. You named the variable testString, but really the value of testString is the object {"string":[""]},"Id":310}

If you want something other than raw json data inside the text box you will need to access the two fields inside test and concatenate them into the format you want. If raw json is ok see @tobyodavies excellent answer. :)

0

精彩评论

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