0

I have a problem with saving data to the localstorage of the browser.

I have a php file and a switch. When the type is "favorites" I make a create a button and send the json data to a function "save" in my javascript.

case 'favorites':
            $session = $m->session;

            $data = json_encode((array)$session);

            echo "<a onclick='save(".$data.")' style='cursor:pointer;' class='metacell'>
                    <img src='".buildUri('images/icons/favorite.png')."' width='16' />
                    <span>Add to favorites</span>
                    </a>";
            break;  

This is my javascript:

function save(data)
    {
        var thedata = data;

        // STORE THE ABOVE DATA IN LOCALSTORAGE
        localStorage.setItem('data', "testje");
    }

I'm currently testing with just some text "testje". When i push the button it goes in localstorage but when I refresh the page its gone ...

Does anbody know how this comes?

4

3 回答 3

0
function save(data)
    {

        // STORE THE ABOVE DATA IN LOCALSTORAGE
        window.localStorage.setItem('data', data);
    }

试试看!localStorage 可能已经成为一个全局变量(在页面的上下文中)并且根本没有指向真正的 localStorage

于 2013-04-18T09:22:12.037 回答
0

尝试这个:

 var thedata ;

function save(data)
{
    thedata = data;

    localStorage.thedata="testje";
}
于 2013-04-18T08:41:17.133 回答
0

您正在使用 HTML 属性来传输值,尽管您没有对值进行任何 HTML 编码。这可能会破坏您的代码。如果您要验证您的 HTML 源代码,您可能已经看到了。所以首先验证(安装一个自动为您执行此操作的浏览器扩展程序)。

此外,您需要对onclick属性值进行 HTML 编码:

echo "<a onclick='save(", htmlspecialchars($data), ")' s [...]
                          ^^^^^^^^^^^^^^^^

http://php.net/htmlspecialchars

于 2013-04-18T08:41:26.733 回答