未捕获的ReferenceError;'abc'未在jquery

时间:2017-10-12 23:19:00

标签: javascript jquery html html5

我有一个带按钮的html表。单击按钮时,我调用ajquery函数,该函数将对我的后端服务进行GET调用。

Html页面行创建如下;

!DOCTYPE html>
<html>
<head> 
<script src="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous">
</script>
<style>
table, th, td {
    border: 1px solid black;
}
</style>
<meta charset="UTF-8">
<title>Clients</title>
</head>
<body>
<table style="width:100%" id="clients_data">
<caption>Clients</caption>
  <tr>
    <th>Clients</th>
    <th>Number of Sites</th> 
    <th>Reset the Processing</th> 
  </tr>
  </table>

<!-- --Java script Functions  -->

<script>
function loadCustomers() {
    $.ajax({
        type: 'GET',
        url: 'http://localhost:8080/cache/getCustomers',
        dataType: 'json',
        success: function(data) {
            var rows = [];
            $.each(data,function(id,value) {
                rows.push('<tr><td><a href="clientSiteInfo.html?client='+id+'">'+id+'</td><td>'+value+'</td><td><button type="button" onclick="reset('+id+')">Reset</td></tr>');
            });
            $('table').append(rows.join(''));
        }
    });
};


function reset(id) {
    alert(id)
    $.ajax({
        type: 'GET',
        url: 'http://localhost:8080/cache/reset?clientName='+id,
        success: function(data) {
          alert("Reset success")
        }
    });
};

window.onload = loadCustomers;
</script>
</body>
</html>

我的重置功能就像;

function reset(id) {
    alert(id)
    $.ajax({
        type: 'GET',
        url: 'http://localhost:8080/cache/reset?clientName='+id,
        success: function(data) {
          alert("Reset success")
        }
    });
};

当我尝试点击按钮时,我希望它必须将“ id ”值传递给我的 reset()函数

点击按钮后,我得到了;

 ReferenceError: testClient is not defined
    at HTMLButtonElement.onclick ((index):1)
onclick @ (index):1

我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

创建行时:

// This is your code
$.each(data,function(id,value) {
  rows.push('<tr><td><a href="clientSiteInfo.html?client='+id+'">'+id+'</td><td>'+value+'</td><td><button type="button" onclick="reset('+id+')">Reset</td></tr>');
});

您将id添加到按钮的onclick属性中。它看起来像这样:

<button type="button" onclick="reset(testClient)">

你希望它看起来像这样:

<button type="button" onclick="reset('testClient')">

如果没有这些额外的引号,你没有传递一个字符串,你传递一个变量的值(从未定义过)。

解决方案是将这些引号添加到HTML模板中:

$.each(data,function(id,value) {
  rows.push('<tr><td><a href="clientSiteInfo.html?client='+id+'">'+id+'</td><td>'+value+'</td><td><button type="button" onclick="reset(\''+id+'\')">Reset</td></tr>');
});