最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why am I getting [object Object] instead of JSON? - Stack Overflow

programmeradmin10浏览0评论

This is the script:

$("#some_button").click(function() {

    var changed = [];

    $( 'input[id$="_1"]' ).each(function() {

        var new_id = this.id.replace( '_1', '_0' );

        if ( $(this).val() !== $( 'input#' + new_id ).val() ) {

            changed.push({id:new_id, new_val:$('input#' + new_id).val(), old_val:$(this).val()});

        }

    });

    alert(changed);

});

and it's gives me [object Object],[object Object].

What am I doing wrong?

This is the script:

$("#some_button").click(function() {

    var changed = [];

    $( 'input[id$="_1"]' ).each(function() {

        var new_id = this.id.replace( '_1', '_0' );

        if ( $(this).val() !== $( 'input#' + new_id ).val() ) {

            changed.push({id:new_id, new_val:$('input#' + new_id).val(), old_val:$(this).val()});

        }

    });

    alert(changed);

});

and it's gives me [object Object],[object Object].

What am I doing wrong?

Share Improve this question asked Jul 14, 2011 at 9:21 naminami 1,2665 gold badges20 silver badges22 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 11

Because you don't have JSON. You have an array: []. JSON is a string representation of a javascript object.

You could use the JSON.stringify method to generate a JSON string from an existing object:

alert(JSON.stringify(changed));

The JSON.stringify method is native in modern browsers but if you need to support legacy browsers you will need to include json2.js to your page. This script checks whether the browser supports natively JSON.stringify and uses it, or if it doesn't it provides a sample implementation.

JSON is one way to display/encode JavaScript objects, but it's not used by default. When you convert an object to a string you'll normally just get a useless value like "[object Object]".

If you want to convert your object into a JSON string, you need to use the JSON.stringify function. (This is included in new browsers, but requires a JSON library in older ones.)

In your case, you probably want to replace your alert line with

alert(JSON.stringify(changed));
发布评论

评论列表(0)

  1. 暂无评论