简体   繁体   中英

Uncaught SyntaxError: Unexpected token (Script Ajax Call)

i'm doing in CQ5 , a component that connect with a servlet and get this info:

Output Servlet (json format)= [{"text":"A","value":10},{"text":"B","value":20}]

for show A and B in a drop down menu.

This my html code:

<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>

For insert the options (select), i do this javascript in the jsp of component:

<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>

But I get Uncaught typeerror undefined is not a function . Maybe I have an error of syntax in my script code. How can I solve?

There are a conflict between 2 jQuery:

We can delete one or modify the code like this:

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

Your code appears to work, only problem I found was that you are not specifying a request type in your AJAX call.

Just add: type: 'post',

Here is a JSFiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM