开发者

Parsing JSON with eval

开发者 https://www.devze.com 2022-12-24 00:34 出处:网络
I have this code: function useHttpResponse() { if (xmlhttp.readyState==4 ) { va开发者_如何转开发r response = eval(\'(\'+xmlhttp.responseText+\')\');

I have this code:

function useHttpResponse() 
{

 if (xmlhttp.readyState==4 )
 {
 va开发者_如何转开发r response = eval('('+xmlhttp.responseText+')');
  alert(response);
 for(i=0;i<response.Users.length;i++)
        alert(response.Users[i].UserId);

 }
}

When i alert, the first alert is "[object Object]"

Why is that so? I need to remove that...how?


Decoding a JSON string converts it into a native JavaScript object. When you alert() it, the object's toString() method is called to cast the object back to a string. Any object cast to a string becomes [object Object]. Consider the following example:

var myObj = new Object();
alert (myObj);            // alerts [object Object]
alert (myObj.toString()); // alerts [object Object]
alert (({}).toString());  // alerts [object Object]

If you want to JSON encode the object again, you can use the JSON.stringify() method found in modern browsers and provided by json2.js.

var myObj = {"myProp":"Hello"};
alert (JSON.stringify(myObj));    // alerts {"myProp":"Hello"};


Why is that so?

Because that is what you get when you convert a simple object to a string.

I need to remove that...how?

Delete alert(response); from your source

0

精彩评论

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

关注公众号