FF 13、IE 9:JSON 字符串化/地理定位对象 [英] FF 13, IE 9: JSON stringify / geolocation object

查看:20
本文介绍了FF 13、IE 9:JSON 字符串化/地理定位对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让 Firefox 13 将地理定位对象转换为 JSON 字符串,但它返回的是一个空字符串,而不是我的 JSON 对象的正确字符串表示.这在最新版本的 Chrome 和 Safari 以及 Android 浏览器中运行良好.这是我的代码:

I'm trying to get Firefox 13 to turn a geolocation position object into a JSON string, but it's returning an empty string rather than the correct string representation of my JSON object. This is working fine in the latest versions of Chrome and Safari, as well as the Android browser. Here's my code:

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition( 
        function (position) {  
            //Success handler
            console.log(position); //This outputs the position object to the console
            var gps = JSON.stringify(position); 
            console.log(gps); //This outputs an empty string!
        }, 
        function (error)
        {   
            //Handle error
        },
        { maximumAge: 3000, timeout: 60000, enableHighAccuracy: true }
        );
}
else {
    //Handle error
}

在 Chrome 中,这会输出一个地理定位对象,以及这个字符串:

In Chrome, this outputs a geolocation object, and this string:

"{"coords":{"latitude":XYZ,"heading":null,"accuracy":40,"altitudeAccuracy":null,"altitude":null,"longitude":XYZ,"speed":null},"timestamp":1339712284200}"

然而,在 Firefox 13 中,输出只是一个空字符串,即使打印到控制台的地理定位对象的所有意图和目的与 Chrome 显示的对象相同.关于这里出了什么问题的任何想法? 似乎是一个相关的问题,但我也没有看到解决方案.顺便说一下,IE9 显示了相同的行为.

However, in Firefox 13 the output is just an empty string, even though the geolocation object that's printed to the console is to all intents and purposes the same as the object displayed by Chrome. Any ideas on what's going wrong here? This seems to be a related issue, but I don't see a solution there either. IE9 displays the same behaviour, by the way.

推荐答案

实际情况是 JSON.stringify 默认只查看对象自身的属性.

What's going on is that JSON.stringify only looks at the object's own properties by default.

并且根据 DOM 规范,所有 DOM 属性实际上都存在于对象的原型上.

And per DOM specs all DOM properties actually live on the object's prototype.

IE 和 Firefox 通过将属性放在原型上来正确实现规范.Chrome 和 Safari 没有:它们将属性直接放在对象上.这使得这个案例有效,但破坏了其他东西(例如挂钩属性 getter 和 setter 的能力)......

IE and Firefox implement the spec correctly by putting the properties on the prototype. Chrome and Safari do not: they put the properties directly on the object. That makes this case work, but breaks other things (e.g. the ability to hook the property getters and setters)....

有人谈论将 toJSON 方法添加到一些 DOM 对象中,以便为 JSON.stringify 提供更合理的行为.

There's talk of adding toJSON methods to some DOM objects to give them more reasonable behavior for JSON.stringify.

这篇关于FF 13、IE 9:JSON 字符串化/地理定位对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆