为什么我得到[object Object]而不是JSON? [英] Why am I getting [object Object] instead of JSON?
问题描述
这是剧本:
$("#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);
});
它给了我 [object Object],[object Object]
。
我做错了什么?
推荐答案
因为你没有JSON。你有一个数组: []
。 JSON是javascript对象的字符串表示。
Because you don't have JSON. You have an array: []
. JSON is a string representation of a javascript object.
您可以使用 JSON.stringify
方法生成JSON来自现有对象的字符串:
You could use the JSON.stringify
method to generate a JSON string from an existing object:
alert(JSON.stringify(changed));
JSON.stringify
方法是原生的现代浏览器,但如果您需要支持旧版浏览器,则需要在页面中包含 json2.js 。此脚本检查浏览器是否支持本机 JSON.stringify
并使用它,如果不支持,则提供示例实现。
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.
这篇关于为什么我得到[object Object]而不是JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!