从localStorage检索数据时,Javascript Uncaught ReferenceError

时间:2016-03-20 19:48:13

标签: javascript jquery ajax html5

我编写的以下代码仅在localStorage值为整数或值仅由数字组成时才有效。我是Javascript的新手,所以答案可能就在我面前......

<html>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <div id="test"></div>
</body>
</html>

<script type="text/javascript">

    localStorage.setItem('test', '12345');
    localStorage.setItem('foo', 'bar');
    localStorage.setItem('john', 'doe');
    localStorage.setItem('carl', 14);

            var name, content;
            for (var key in localStorage) {
                $("#test").append('<button onclick="senddata('+localStorage[key]+')">'+key+'</button>');
            }

    function senddata(content) {
    $.post("processor.php",
       {text: content},
       function(response){
           console.log(response);
       }
          );
    }
</script>

按下代码生成的按钮时,控制台中会显示以下内容

Uncaught ReferenceError: bar is not defined
Uncaught ReferenceError: doe is not defined
14
12345
14

processor.php

if (isset($_POST['text']))
    die($_POST['text']);

我做错了什么?感谢您阅读:)

2 个答案:

答案 0 :(得分:0)

更改

void work_with_range(
        std::chrono::system_clock::time_point from = {}
        , std::chrono::system_clock::time_point to = {}
        )
{
    std::cout << "Will work with range from "
         << ( from == decltype(from)()
              ? std::put_time( nullptr, "beginning" )
              : std::put_time( utc( from ), "%Y-%m-%d %H:%M:%S" )
            )
         << " to "
         << ( to == decltype(to)()
              ? std::put_time( nullptr, "end" )
              : std::put_time( utc( to ), "%Y-%m-%d %H:%M:%S" )
            )
         << "."
         << std::endl;
    // ...
}

$("#test").append('<button onclick="senddata('+localStorage[key]+')">'+key+'</button>');

否则会尝试发送未定义变量$("#test").append('<button onclick="senddata(\''+localStorage[key]+'\')">'+key+'</button>'); bar)而不是字符串sendata(bar)'bar')。

答案 1 :(得分:0)

数字文字是裸露的。例如123

但字符串文字总是需要单引号或双引号。例如。 'foo'"foo"

检查您是否根据需要引用了字符串文字。

另外,你试过调试吗?逐步完成您的脚本,以确切了解发生了什么和不发生什么。您可能在某些时候也会遇到错误。

相关问题