Uncaught SyntaxError: Unexpected token (Script Ajax Call)

Uncaught SyntaxError: Unexpected token (Script Ajax Call)

我在 CQ5 中做,一个与 servlet 连接并获取此信息的组件:

Output Servlet (json format)= [{"text":"A","value":10},{"text":"B","value":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>

为了插入选项 (select),我在组件的 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。也许我的脚本代码中有语法错误。我该如何解决?

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

只需添加:type: 'post',

这里是JSFiddle.

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>');
            }
    });
})