How to call AJAX request on dropdown change event?

2019-01-20 01:29发布

index.php

<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>

<a href='one.php' class='ajax'>One</a>
<a href='two.php' class='ajax'>Two</a>

<div id="workspace">workspace</div>

one.php

$arr = array ( "workspace" => "One" );
echo json_encode( $arr );

two.php

$arr = array( 'workspace' => "Two" );
echo json_encode( $arr );

ajax.js

jQuery(document).ready(function(){
    jQuery('.ajax').live('click', function(event) {
        event.preventDefault();
        // load the href attribute of the link that was clicked
        jQuery.getJSON(this.href, function(snippets) {
            for(var id in snippets) {
                // updated to deal with any type of HTML
                jQuery('#' + id).html(snippets[id]);
            }
        });
    });
});

Above code is working perfectly. When I click link 'One' then String 'One' is loaded into workspace DIV and when I click link 'Two' then String 'Two' is loaded into workspace DIV.

Question:

Now I want to use a dropdown to load one.php and two.php in workspace DIV instead of links in index.php. When I use link then I use class='ajax' in link properties but how to call ajax request on drop down change event ?

Thanks

2条回答
何必那么认真
2楼-- · 2019-01-20 02:21

Change your code like this:

jQuery('#dropdown_id').live('change', function(event) {
    jQuery.getJSON($(this).val(), function(snippets) {
        for(var id in snippets) {
            // updated to deal with any type of HTML
            jQuery('#' + id).html(snippets[id]);
        }
    });
});

And your dropdown should look like this:

<select id="dropdown_id">
  <option value="one.php">One</option>
  <option value="two.php">Two</option>
</select>
查看更多
来,给爷笑一个
3楼-- · 2019-01-20 02:22

Assign the href as list item values in drop down. Onchange of dropdown, make the ajax call.

class name "ajax" is just for reference (useful, if you want to handle event for morethan one element).

查看更多
登录 后发表回答