Django项目中jQuery Ajax请求URL重复问题求助
Hey there! Let's break down why your Ajax request URL is showing up as http://127.0.0.1:8000/myportfolio/add_transaction/myportfolio/add_transaction instead of the expected http://127.0.0.1:8000/myportfolio/add_transaction/—and how to fix it.
The Root Cause: Relative vs. Absolute Paths
The most likely issue is that you're using a relative path in your jQuery Ajax code, and your current page URL is already http://127.0.0.1:8000/myportfolio/add_transaction/.
For example, if your Ajax code looks something like this:
$.ajax({ url: 'myportfolio/add_transaction', // No leading slash method: 'GET', // ... other settings });
Browsers will interpret this relative path as "append this to the current page's URL", resulting in the duplicated path you're seeing.
Quick Fixes to Correct the URL
1. Use an Absolute Path (Simple & Direct)
Add a leading slash to your Ajax URL to tell the browser to start from the root of your domain:
$.ajax({ url: '/myportfolio/add_transaction/', // Leading slash = root-relative method: 'GET', // ... other settings });
This will point directly to the correct endpoint every time, regardless of the current page's URL.
2. Use Django's URL Reverse Resolution (Recommended)
Hardcoding URLs can lead to issues later if you change your urls.py paths. Instead, use Django's built-in URL reversing to dynamically get the correct URL:
First, make sure your urls.py has a name for the endpoint:
# urls.py from django.urls import path from . import views urlpatterns = [ path('myportfolio/add_transaction/', views.add_transaction, name='add_transaction'), # ... other paths ]
Then, in your template, pass this URL to your JavaScript code:
<!-- In your Django template --> <script> // Capture the reversed URL in a JS variable const addTransactionUrl = "{% url 'add_transaction' %}"; </script>
Now use this variable in your Ajax call:
$.ajax({ url: addTransactionUrl, method: 'GET', // ... other settings });
This ensures your URL always matches what's defined in urls.py, even if you update the path later.
Bonus: Don't Forget to Handle GET Requests in Your View
You mentioned you haven't modified your view to adapt to GET requests—once the URL is fixed, update your view to handle GET properly. For example:
# views.py from django.http import JsonResponse def add_transaction(request): if request.method == 'GET': # Add your GET request logic here (e.g., fetch data to return) return JsonResponse({ 'status': 'success', 'message': 'GET request handled correctly' }) # Handle other request methods (POST, etc.) here if needed return JsonResponse({'status': 'error', 'message': 'Invalid request method'})
内容的提问来源于stack exchange,提问作者SkillSet12345

