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]);
}
});
});
});
以上代码运行良好.当我点击链接一"时,字符串一"被加载到工作区 DIV 中,当我点击链接二"时,字符串二"被加载到工作区 DIV.
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.
问题:
现在我想使用下拉菜单在工作区 DIV 中加载 one.php 和 two.php,而不是在 index.php 中加载链接.当我使用链接时,我在链接属性中使用 class='ajax' 但如何在下拉更改事件上调用 ajax 请求?
谢谢
像这样改变你的代码:
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>
这篇关于如何在下拉更改事件上调用 AJAX 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!