简体   繁体   English

如何从ajax响应中获取对象属性

[英]How to get the Object atributes from ajax response

I make a call to the server using ajax and I return the class instance . 我使用ajax调用服务器,并返回类实例。

My return ajax response looks like follows. 我的返回ajax响应如下所示。

  Object { id=1362570046980 , creationDate=1362570046980, type="PUBLIC"}

hOw i can get the values of id , creationDate and type from this object. 我可以从此对象获取id,creationDate和type的值。

use . 使用. operator get the objects value.. however the obect which you are gettin is weird.. not JSON.. so make sure it is returning json 运算符获取对象的值..但是,您正在获取的对象很奇怪..不是JSON ..因此请确保它返回的是json

say your object is data 说你的对象是数据

alert(data.id) //gives you 1362570046980 
alert(data.creationDate) //gives you 1362570046980 
alert(data.type) //gives you PUBLIC

Try like this: 尝试这样:

var myobject = yourAjaxResponseObject;

alert(myobject.id);
alert(myobject.creationDate);
alert(myobject.type);

Map a variable to your object/response, and access it's properties, etc, in that way as described up above. 如上所述,将变量映射到您的对象/响应,并访问其属性等。

You need to specify a callback function in your ajax function to which an object will be passed containing the response. 您需要在ajax函数中指定一个回调函数,一个包含响应的对象将传递给该回调函数。

$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" },
complete: function(data){ //This is the callback function
  alert(data.id);
  alert(data.creationDate);
  alert(data.type);
}
});

As you can see you can then access the properties in the json using simple dot notation. 如您所见,您可以使用简单的点符号访问json中的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM