简体   繁体   English

如何在下拉列表更改事件上调用AJAX请求?

[英]How to call AJAX request on dropdown change event?

index.php 的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 one.php

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

two.php two.php

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

ajax.js 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. 当我单击链接'One'时,字符串'One'被加载到工作区DIV中,当我单击链接'Two'时,字符串'Two'被加载到工作区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. 现在我想使用下拉列表在工作区DIV中加载one.php和two.php而不是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 ? 当我使用链接时,我在链接属性中使用class ='ajax'但是如何在下拉更改事件中调用ajax请求?

Thanks 谢谢

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>

Assign the href as list item values in drop down. 在下拉列表中将href指定为列表项值。 Onchange of dropdown, make the ajax call. 更改下拉列表,进行ajax调用。

class name "ajax" is just for reference (useful, if you want to handle event for morethan one element). 类名“ajax”仅供参考(如果您想处理超过一个元素的事件,则非常有用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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