Vitalii Ponomar
Vitalii Ponomar

Reputation: 10946

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

Upvotes: 1

Views: 1544

Answers (3)

Quentin
Quentin

Reputation: 944442

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.

Upvotes: 1

Quentin
Quentin

Reputation: 944442

If you are loading just JavaScript, then use getScript instead of load.

If you are loading a combination of HTML then JavaScript, then I would give serious consideration to refactoring so that the JavaScript is already in place and events are handled using live instead of being bound directly to the elements themselves.

Upvotes: 0

user956584
user956584

Reputation: 5558

You can use eval to execute javascript code

eval(ajax.request);

Upvotes: 1

Related Questions