Search code examples
javascriptajaxjqueryjquery-load

AJAX - how to load javascript code not html?


I use jQuery with $('#countryid').load('/some/url',{country: country_id}); function to automatically load options for regions depending on selected country before.

And it works fine when I load html through ajax.

But I need to load javascript code. When I try to do that all select fields disappear from page at all...

What am I doing wrong?

Code:

<script type="text/javascript">
$(document).ready(function() {
    $('#countrydropdown').change(function() {
        var countryvalue = $('#countrydropdown option:selected').val();
        if(countryvalue==0){clearlist();}
        getarea();
    });
});
function getarea(){
    var countryvalue = $('#countrydropdown option:selected').val();
    var area = $('#areadropdown');
    if(countryvalue==0){
        area.attr("disabled",true);
    }else{
        area.attr("disabled",false);
        area.load('/ajax/2/',{country: countryvalue});
    }
}
function clearlist(){
    $('#areadropdown').empty();
}
</script>

<form action="" id="form">
    <select id="countrydropdown">
        <option value="0">Countries</option>
        ...
    </select>
    <select id="areadropdown" disabled="disabled">

    </select>
</form>

Thanks!!!


Solution

  • Based on the code your comment on my previous answer suggests you are using:

    <script type="text/javascript">for(var i in arr) document.write(arr[i]);</script>

    After the page has loaded, the document will enter the closed state.

    You cannot document.write to a document in the cosed state, so document.open will be automatically called.

    This will trash the existing document so a new one can be written.

    Use DOM to manipulate the document, don't go near document.write.