如何用JQuery从指定URL获取特定Div且不加载完整页面?
Hey there, I took a look at your code and spotted a few key issues that are preventing your modal button from working properly. Let's walk through each fix step by step:
1. Correct the jQuery Selector
You’re using $(response).find('testblock') to target the div, but testblock is an ID, not a tag name. You need to use the ID selector #testblock to grab the right element:
$(response).find('#testblock').each(function(){ $('#main').append($(this).html()); });
2. Remove Duplicate jQuery Imports
Your page loads two versions of jQuery (3.4.1 and 1.9.1) at the same time. This causes version conflicts that break core jQuery and Bootstrap functionality. Keep just the newer, supported version:
<!-- Delete this conflicting line --> <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
3. Use GET Instead of POST for Fetching the Page
You’re using $.post to retrieve a static page, but GET is the appropriate HTTP method for fetching resources. POST is designed for submitting data to a server, not pulling content:
$(document).ready(function(){ $.get("https://localhost:44330/",{},function(response){ $(response).find('#testblock').each(function(){ $('#main').append($(this).html()); }); }); });
4. Ensure Dynamic Modal Triggers Work
Bootstrap’s built-in event delegation usually handles data-toggle buttons even when they’re added dynamically, but if you still run into issues, you can add explicit event delegation to guarantee the button triggers the modal:
// Optional: Add this if the button still doesn't respond after fixes $(document).on('click', '[data-toggle="modal"]', function(e) { e.preventDefault(); const targetModal = $(this).data('target'); $(targetModal).modal('show'); });
Full Fixed Script Section
Here’s what your script block should look like after applying all fixes:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> <script> $(document).ready(function(){ $.get("https://localhost:44330/",{},function(response){ $(response).find('#testblock').each(function(){ $('#main').append($(this).html()); }); }); // Optional event delegation for dynamic buttons $(document).on('click', '[data-toggle="modal"]', function(e) { e.preventDefault(); const targetModal = $(this).data('target'); $(targetModal).modal('show'); }); }); </script>
One final check: If your app and the target URL (https://localhost:44330) are on different ports, you’ll run into CORS restrictions. You’ll need to configure the target server to allow requests from your app’s origin, or run both apps on the same domain/port.
内容的提问来源于stack exchange,提问作者Leroi

