简体   繁体   English

JavaScript中的对象到字符串的转换问题

[英]Object to String Conversion Issue in JavaScript

I have a JQuery that records all the immediate parent lists when a child list is clicked. 我有一个JQuery,它在单击子列表时记录所有直接父列表。

Example - 范例-

- Parent1  
  - Child1
     - GrandChild1
     - Grandchild2
     - Grandchild3
  - Child2
     - Grandchild4
     - Grandchild5

Clicking on Grandchild2 will record Parent1, Child1 and Grandchild2. 单击Grandchild2将记录Parent1,Child1和Grandchild2。

I want to use JQuery, JS and Cookies to print a value in another page when something is clicked in this list page. 当在此列表页面中单击某些内容时,我想使用JQuery,JS和Cookies在另一个页面中打印值。 However the following codes doesn't work. 但是,以下代码不起作用。 Kindly help. 请帮助。

JQUERY and JS Code - (for the list page) JQUERY和JS代码- (用于列表页面)

function objToString (obj) {
            var str = '';
            for (var p in obj) {
                if (obj.hasOwnProperty(p)) {
                    str += p + '::' + obj[p] + '\n';
                }
            }
            return str;
        }

        $(document).ready(function() {
            $('li').click(function() {
                var obj = $(this).parents('li').add(this);
                obj.css('color', 'red');
                var data= "data=";
                document.cookie = data+objToString(obj);
            });
        });

PHP Code - (for the page where the list data is to be printed) PHP代码- (用于要打印列表数据的页面)

echo $_COOKIE['data'];

The PHP Code should print Parent1 Child1 Grandchild2 for the above example. 对于上面的示例,PHP代码应显示Parent1 Child1 Grandchild2 Also all functionalities should be IE 7 compatible. 同样,所有功能都应与IE 7兼容。 Only problem I face is that objToString doesn't work properly here. 我面对的唯一问题是objToString在这里无法正常工作。

Use JSON.stringify instead. 请改用JSON.stringify。 This function converts any Object to String, concatinating the keys and values. 此函数将任何Object转换为String,并保留键和值。

Example:- 例:-

var obj = {a:"b", f:{c:"d"},e:"e"};
JSON.stringify(obj); 

Output:- 输出: -

"{"a":"b","f":{"c":"d"},"e":"e"}" . “ {” a“:” b“,” f“:{” c“:” d“},” e“:” e“}”。

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

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