未捕获的SyntaxError:意外的令牌(脚本Ajax调用)

时间:2015-04-01 08:47:14

标签: javascript jquery ajax servlets cq5

我正在进行CQ5,这是一个与servlet连接并获取此信息的组件:

  

输出Servlet(json格式)= [{" text":" A"," value":10},{" text&#34 ;:" B""值" 20}]

显示下拉菜单中的节目A和B.

这是我的HTML代码:

<div>
   <form action="/bin/company/repo" method="post">
        <select id="options">
        </select>
    <input type="submit" id="send" value="Send">  
    </form>
    <p id="demo"></p>
</div>

为了插入选项(选择),我在组件的jsp中执行此javascript:

<script type="text/javascript">
    //get a reference to the select element
    $select = $('#options');
    //request the JSON data and parse into the select element
    $.ajax({
      url: '/bin/company/repo',
      dataType:'JSON',
      success:function(data){
        //clear the current content of the select
        $select.html('');
        //iterate over the data and append a select option
        $.each(data, function(text, value){
          $select.append('<option id="' + value.value + '">' + value.text + '</option>');
        });
      },
      error:function(){
        //if there is an error append a 'none available' option
        $select.html('<option id="-1">none available</option>');
      }
    });
</script>

但我得Uncaught typeerror undefined is not a function。也许我的脚本代码中有语法错误。我怎么解决?

2 个答案:

答案 0 :(得分:1)

2 jQuery之间存在冲突:

我们可以删除一个或修改如下代码:

<script type="text/javascript">
var j = jQuery.noConflict();
j(document).ready(function(){
    //get a reference to the select element
    //request the JSON data and parse into the select element
    j.ajax({
            url: '/bin/company/repo',
            dataType:'JSON',
            success:function(data){
              //clear the current content of the select
              j('#abcd').html('');
              //iterate over the data and append a select option
              jQuery.each(data, function(text, value){
                 j('#abcd').append('<option id="' + value.value + '">' + value.text + '</option>');
              });
            },
            error:function(){
               //if there is an error append a 'none available' option
               j('#abcd').html('<option id="-1">none available</option>');
            }
    });
})

答案 1 :(得分:0)

您的代码似乎有效,只有我发现的问题是您没有在AJAX调用中指定请求类型。

只需添加:type: 'post',

这是JSFiddle