jquery ajax 数据显示[object Object]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18062951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery ajax data shows [object Object]
提问by tawheed
I have a very basic ajax call to alert the data that was reported from the server
我有一个非常基本的 ajax 调用来提醒从服务器报告的数据
$.ajax({
type: "POST",
url: "/someform/act", //edit utl to url
data: { changed: JSON.stringify(plainData) }, //edit to include
success: function(data) {
alert(data); //data not $data
},
error: function() {
//error condition code
}
});
According to the docson the jquery website regarding data field on the success callback, it says that data returned is the data from the server. However for some strange reason when I alert $data
, I get [object Object]
根据jquery网站上关于成功回调数据字段的文档,它说返回的数据是来自服务器的数据。然而,由于一些奇怪的原因,当我提醒时$data
,我得到[object Object]
I was expecting to see something like this, since that is what the server would send back
我期待看到这样的东西,因为那是服务器会发回的东西
<status>0</status>
EDIT:
编辑:
data is also passed along as the POST
数据也作为 POST 传递
采纳答案by moonwave99
alert()
prints the string representation of the arguments - hence if you pass an object, you'll get [object Object]
.
alert()
打印参数的字符串表示 - 因此,如果您传递一个对象,您将获得[object Object]
.
To inspect data, use console.log(data)
better.
要检查数据,请console.log(data)
更好地使用。
回答by MightyPork
You need to use JSON.stringify(data)
in the alert
to get anything readable.
你需要使用JSON.stringify(data)
inalert
来获得任何可读的东西。
Also, $data
is a completely different variable name than data
.
此外,$data
是一个完全不同的变量名data
。
回答by L105
If you server send a JSON, you need to put dataType: 'json'
to your ajax call. Be aware there's some mistake in your ajax call.
如果您的服务器发送 JSON,则需要放入dataType: 'json'
ajax 调用。请注意,您的 ajax 调用中存在一些错误。
$.ajax({
type: "POST",
url: "/someform/act", // NOT 'UTL',
data: {
key: value,
key2: value2
},
// or data: plaindata, // If 'plaindata' is an object.
dataType: 'json',
success: function(data) {
console.log(data); // As moonwave99 said
},
error: function() {
//error condition code
}
});
EDIT
编辑
When sending data, you should send an object. jQuery will handle the array to sned it to the server. So if plain data is an object, it should be like this
发送数据时,应该发送一个对象。jQuery 将处理数组以将其发送到服务器。所以如果普通数据是一个对象,它应该是这样的
data: plainData,