简体   繁体   English

使用jQuery / Ajax从下拉列表中进行选择,从同一页面上的另一个div加载内容

[英]Load content from another div on same page with on select from dropdown using jQuery/Ajax

I know this is very common question and has multiple solutions already available but I am not able to find a proper solution to the question I had 我知道这是一个非常常见的问题,已经有多种解决方案,但是我无法找到我所遇到问题的合适解决方案

I have a dropdown list, from where when user select the dropdown, the selection loads a div that is defined in the same page. 我有一个下拉列表,当用户选择下拉列表时,选择将从其中加载在同一页面中定义的div。 It works fine, I have implemented it as follows: 它工作正常,我将其实现如下:

<select id="selectMe">
    <option value="val1">opt1</option>
    <option value="val2">opt2</option>
    </select>

<div id="val1" class="group"> content1</div>
<div id="val2" class="group">content2</div>

Jquery :: jQuery ::

$(document).ready(function() {
  $('.group').hide();
  $('#val1').show();
  $('#selectMe').change(function() {
    $('.group').hide();
    $('#' + $(this).val()).show();
  })
});

Now, this serves my purpose but takes a lot of time to load the divs as they contain huge data in them (Iframes, external calls) and page is taking lot of time (almost half a minute) to load all the divs before displaying the first div which is pre selected, I am trying to use ajax as I understood that we can dynamically load other divs upon selection instead of loading them all at once on page load, i tried removing documet.ready() with windows.load function, but it didn't work. 现在,这符合我的目的,但是加载div时需要花费很多时间,因为它们中包含大量数据(iframe,外部调用),而在显示div之前,页面要花费大量时间(几乎半分钟)来加载所有div。我首先尝试使用预定义的div,因为我了解我们可以在选择时动态加载其他div,而不是在页面加载时一次全部加载它们,因此我尝试使用windows.load函数删除documet.ready(),但这没用。 If i am missing something, can some one please help me out in solving the issue. 如果我缺少任何东西,请有人帮我解决问题。

Update1: 更新1:

The code works fine, i donot have any problem with it. 该代码工作正常,我没有任何问题。 I want to load only selected div at once instead of loading all the div's ( About 500) along with the page as it is taking lot of time to load because of huge data (div's -About 500 in number containing Iframe's). 我想一次只加载选定的div,而不是同时加载所有div(约500个)和页面,因为由于海量数据(div约为-包含iframe的数量约为500个),这会花费大量时间。
Instead I want to load each div separately dynamically only on selection or restrict load to only fewer number 相反,我想仅在选择时动态地分别加载每个div或将加载限制为仅较少数量

Update2: 更新2:

The div contains the data as follows: div包含以下数据:

<div id="val1" class="group">
 <iframe class="DZembed-table" src="//www.datazoa.com/data/table.asp?a=view&th=1A7400B7A3&dzuuid=423&uid=dzadmin" frameborder="0" width="800px" height="270px">Unavailable - Anderson County, Ks - Total Employment (not seasonally adjusted)</iframe>

/* Some text about 10-15 lines */ / *大约10-15行的文字* /

</div>

I have about 500 in number of such div's 我大约有500个这样的div

for reference, please visit this page as example and it almost takes the same time to load the page I wanted to change 供参考,请以此页面为例,加载我要更改的页面几乎需要花费相同的时间

url: http://kansaseconomy.org/economic-indicators/total-nonfarm-employment-bls 网址: http//kansaseconomy.org/economic-indicators/total-nonfarm-employment-bls

Try first to hide .group with CSS display: none; 首先尝试用CSS display: none;隐藏.group display: none; instead of jQuery .hide() at first and see if it's enough for you. 而不是首先使用jQuery .hide()查看它是否足以满足您的需求。

Ok I think I get the issue. 好吧,我想我明白了。 It was unclear before that all the divs already have all the data in them and it just takes a long time to render all of them on the initial page load. 目前尚不清楚所有div中是否已包含所有数据,并且在初始页面加载时渲染所有这些仅需要很长时间。 You have to remove the content of the divs from the main HTML and put them in a javascript data area or in other documents in order to delay rendering of the HTML in each div. 您必须从主HTML中删除div的内容,并将它们放在javascript数据区域或其他文档中,以延迟每个div中HTML的呈现。

Since each seems to just load the data into an iframe, you should load empty divs and in each have an attribute like "fsrc" with the url and dynamically load the source from "fsrc" into the div on your select change event handler. 由于每个似乎都只是将数据加载到iframe中,因此您应该加载空的div,并在每个URL中都具有类似“ fsrc”的属性,并在选择更改事件处理程序上将源从“ fsrc”动态加载到div中。 You can also check if the div was already loaded to avoid repeat calls to the ajax request. 您还可以检查div是否已经加载,以避免重复调用ajax请求。 If you really need iframes you can have those empty inside the divs and use the same method but target the HTML of the iframe rather than the div. 如果您确实需要iframe,则可以在div中留空这些iframe,并使用相同的方法,但以iframe的HTML而不是div为目标。

Here is some starter code but I suspect you might run into a cross origin issue unless you have that resolved already. 这是一些入门代码,但我怀疑您可能会遇到跨源问题,除非您已解决该问题。 HTML: HTML:

<select id="selectMe">
    <option value="val1">opt1</option>
    <option value="val2">opt2</option>
    </select>

<div id="val1" class="group" fsrc="" > content1</div>
<div id="val2" class="group" fsrc="//www.datazoa.com/data/table.asp?a=view&th=1A7400B7A3&dzuuid=423&uid=dzadmin">content2</div>

Javascript: Javascript:

$(document).ready(function() {
  $('.group').hide();
  $('#val1').show();
  $('#selectMe').change(function() {
    $('.group').hide();
    $.ajax({
      url: $('#' + $(this).val()).attr('fsrc') ,
      context: document.body
    }).done(function() {
        $('#' + $(this).val()).html(data);
        $('#' + $(this).val()).show();
    });   
  })
});

There is no error checking also so I leave that to you to solve. 也没有错误检查,所以我留给您解决。

To load the div content with Ajax the first thing you would need to do is split the div content into separate files (or endpoint responses ) 要使用Ajax加载div内容,您需要做的第一件事是将div内容拆分为单独的文件(或端点响应)

For example we can create a file name val1.html: 例如,我们可以创建一个文件名val1.html:

<p>div 1 content...</p>

Then create another file named val2.html: 然后创建另一个名为val2.html的文件:

<p>div 2 content...</p>

Now all you need to do is update your jQuery to get the div content via Ajax to something like this: 现在您需要做的就是更新您的jQuery,以通过Ajax将div内容更改为以下形式:

jQuery(document).ready(function($){
$('.group').hide();
$('#val1').show();
$('#selectMe').change(function() {
$('.group').hide();
var $ele = $('#' + $(this).val());
if( ! $ele.hasClass('ajax-loaded') ) {
    $.ajax({
        method: 'GET',
        url: 'http://example.com/' + $(this).val() + '.html'
    }).success(function(data){
        $ele.html(data);
        $ele.addClass('ajax-loaded');
        $ele.show();
    });
}
else {
    $ele.show();
}
})
});

You have multiple options that don't use <iframe> s. 您有多个不使用<iframe>的选项。 I wouldn't be too concerned about the footprint of your 500 text blocks as they're not super huge. 我不会太在意您的500个文本块的覆盖范围,因为它们并不是很大。

Option A - JS Store 选项A-JS商店

With this option there's a lot less work when it comes to the markup. 使用此选项,标记方面的工作量大大减少。 You don't have to manually or on the server create 100's of content DIVs. 您不必手动或在服务器上创建100个内容DIV。 You simply re-use the same DIV. 您只需重复使用相同的DIV。

 function createOption( value, text ) { var opt = document.createElement( 'option' ); opt.value = value; opt.text = text; return opt; } function buildSelect( options ) { var i = 0; var len = options.length; var frag = document.createDocumentFragment(); for ( ; i < len; i++ ) { frag.appendChild( createOption( i, 'Option ' + ( i + 1 ) ) ); } $list.append( frag ); } var data = [ "Quarter log Blimey hang the jib Davy Jones' Locker tackle boatswain squiffy. Shrouds American Main scallywag wench Blimey furl ye fathom. Holystone keel Pieces of Eight topsail come about Gold Road blow the man down fore. Overhaul mizzen gunwalls black jack long clothes weigh anchor fluke code of conduct. Take a caulk black spot brig fire ship gun long clothes jury mast tender. Ye yardarm to go on account jury mast grog blossom Plate Fleet broadside grog. Scuttle chandler belaying pin pirate gaff hulk pressgang Spanish Main. Topmast chantey crimp yardarm flogging jib line avast. Warp Chain Shot shrouds rum flogging fire ship grapple log. Take a caulk rope's end Plate Fleet log haul wind Blimey keelhaul overhaul.", "Port parrel cog chase Brethren of the Coast scourge of the seven seas pink American Main spike ho. Ahoy Buccaneer Shiver me timbers provost Arr bring a spring upon her cable blow the man down line pillage hempen halter. Provost Letter of Marque code of conduct Sea Legs strike colors scallywag long clothes heave to measured fer yer chains pressgang. Run a rig gabion cackle fruit marooned sutler jolly boat Jolly Roger jib belaying pin killick. Fire ship gally weigh anchor lugsail gun tack league Barbary Coast spyglass Privateer. Spanker killick grog clipper jib dead men tell no tales marooned barque prow grapple. Fore Brethren of the Coast hail-shot poop deck keel boom run a rig line Shiver me timbers splice the main brace. ", "Nelsons folly hulk strike colors lass six pounders bring a spring upon her cable gabion jolly boat. Man-of-war nipper to go on account main sheet scuppers crack Jennys tea cup doubloon Nelsons folly. Barque quarter Jolly Roger jib tender lee brig avast. Transom draft draught scallywag flogging coxswain hail-shot booty. Coffer scurvy grog crack Jennys tea cup grapple provost Plate Fleet ho. Black spot knave draught Shiver me timbers topgallant rum brigantine gaff. Hardtack overhaul Gold Road stern fire ship run a rig haul wind aft. Execution dock parley provost skysail haul wind heave down barque sloop. Plunder grog sloop smartly weigh anchor Pieces of Eight hands bilge. Scallywag keelhaul reef pillage tackle skysail salmagundi man-of-war." ]; var $list = $( '#list' ); var $display = $( '#display' ); $list.on( 'change', function ( e ) { $display.text( data[ this.value ] ); } ); // Insert default. $display.text( data[ 0 ] ); buildSelect( data ); 
 #display { margin: 2rem 1rem; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="list"></select> <div id="display"></div> 

Option B - Store in HTML 选项B-以HTML格式存储

Here you need to manually or with the help of a server side language build 100's of DIVs, including their IDs. 在这里,您需要手动或借助服务器端语言来构建100个DIV,包括其ID。 Which, if doing manually could be a real pain. 如果手动进行操作,那将是真正的痛苦。

 var $list = $( '#list' ); var $options = $( '.option' ); $list.on( 'change', function ( e ) { $options.hide(); $( '#option-' + this.value ).show(); } ); 
 .option { display: none; margin: 2rem 1rem; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="list"> <option value="0">Option 1</option> <option value="1">Option 2</option> <option value="2">Option 3</option> </select> <div id="option-0" class="option" style="display: block;"> Quarter log Blimey hang the jib Davy Jones' Locker tackle boatswain squiffy. Shrouds American Main scallywag wench Blimey furl ye fathom. Holystone keel Pieces of Eight topsail come about Gold Road blow the man down fore. Overhaul mizzen gunwalls black jack long clothes weigh anchor fluke code of conduct. Take a caulk black spot brig fire ship gun long clothes jury mast tender. Ye yardarm to go on account jury mast grog blossom Plate Fleet broadside grog. Scuttle chandler belaying pin pirate gaff hulk pressgang Spanish Main. Topmast chantey crimp yardarm flogging jib line avast. Warp Chain Shot shrouds rum flogging fire ship grapple log. Take a caulk rope's end Plate Fleet log haul wind Blimey keelhaul overhaul. </div> <div id="option-1" class="option"> Port parrel cog chase Brethren of the Coast scourge of the seven seas pink American Main spike ho. Ahoy Buccaneer Shiver me timbers provost Arr bring a spring upon her cable blow the man down line pillage hempen halter. Provost Letter of Marque code of conduct Sea Legs strike colors scallywag long clothes heave to measured fer yer chains pressgang. Run a rig gabion cackle fruit marooned sutler jolly boat Jolly Roger jib belaying pin killick. Fire ship gally weigh anchor lugsail gun tack league Barbary Coast spyglass Privateer. Spanker killick grog clipper jib dead men tell no tales marooned barque prow grapple. Fore Brethren of the Coast hail-shot poop deck keel boom run a rig line Shiver me timbers splice the main brace. </div> <div id="option-2" class="option"> Nelsons folly hulk strike colors lass six pounders bring a spring upon her cable gabion jolly boat. Man-of-war nipper to go on account main sheet scuppers crack Jennys tea cup doubloon Nelsons folly. Barque quarter Jolly Roger jib tender lee brig avast. Transom draft draught scallywag flogging coxswain hail-shot booty. Coffer scurvy grog crack Jennys tea cup grapple provost Plate Fleet ho. Black spot knave draught Shiver me timbers topgallant rum brigantine gaff. Hardtack overhaul Gold Road stern fire ship run a rig haul wind aft. Execution dock parley provost skysail haul wind heave down barque sloop. Plunder grog sloop smartly weigh anchor Pieces of Eight hands bilge. Scallywag keelhaul reef pillage tackle skysail salmagundi man-of-war. </div> 

One modification you could make to this approach is to keep all .option DIVs hidden and to copy to contents of the target DIV to a "display" DIV like I have done in the other examples. 您可以对这种方法进行的一种修改是使所有.option DIV保持隐藏状态,并将目标DIV的内容复制到“显示” DIV中,就像我在其他示例中所做的那样。 Then you don't need to hide() and show() the .option DIVs. 这样,您就无需对.option DIV进行hide()show()了。

Option C - Ajax with JS Cache 选项C-具有JS缓存的Ajax

Below is some pseudo code that has not been tested but should give you an idea of how to setup AJAX (front-end portion) if you really wanted. 下面是一些未经测试的 伪代码 ,但是如果您确实需要,应该可以使您了解如何设置AJAX(前端部分)。

<select id="list">
   <option value="0" selected>Option 1</option>
   <option value="1">Option 2</option>
   <!-- to 500 -->
   <option value="499">Option 3</option>
</select>

<!-- Insert Default option. -->
<div id="display">
    Quarter log Blimey hang the jib Davy Jones' Locker tackle boatswain squiffy. Shrouds American Main scallywag wench Blimey furl ye fathom. Holystone keel Pieces of Eight topsail come about Gold Road blow the man down fore. Overhaul mizzen gunwalls black jack long clothes weigh anchor fluke code of conduct. Take a caulk black spot brig fire ship gun long clothes jury mast tender. Ye yardarm to go on account jury mast grog blossom Plate Fleet broadside grog. Scuttle chandler belaying pin pirate gaff hulk pressgang Spanish Main. Topmast chantey crimp yardarm flogging jib line avast. Warp Chain Shot shrouds rum flogging fire ship grapple log. Take a caulk rope's end Plate Fleet log haul wind Blimey keelhaul overhaul.
</div>
var cache    = {};
var $list    = $( '#list' );
var $display = $( '#display' );

// Append text to display DIV.
function appendText( value ) {
  $display.text( value );
}

// Get text via AJAX.
function getText( opt_id ) {

  var jqxhr = $.ajax( {
    url: '/your/endpoint/',
    data: { id: opt_id },
    method: 'POST'
  } );

  jqxhr.done( function ( data, status , xhr ) {

    // Cache for future use.
    cache[ opt_id ] = data;

    appendText( data );

  } );
  jqxhr.fail( function () {} ); // Handle request failure.
  jqxhr.always( function () {} ); // Run on success or error.

}

$list.on( 'change', function ( e ) {

  if ( cache[ this.value ] ) {
    appendText( cache[ this.value ] );
  } else {
    getText( this.value );
  }

} );

Reference: jQuery.ajax() 参考: jQuery.ajax()

Personally I'd go for option A and then B unless there are some other overriding concerns that I'm not aware of. 就我个人而言,我会选择选项A ,然后再选择B,除非还有其他一些我不知道的首要问题。

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

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