简体   繁体   中英

Redirect to root url in AJAX

I'm looking for a way to start URL with ('') instead of ('search/') in AJAX request. I can workaround this problem simply add new path in URL dispatcher with path('search/email_add/<int:pk>/', views.email_add, name="email_add_from_search") but it's not a DRY method and a RedirectView not satisfy me.

It works properly when I'm using add-phone.js script while in root URL.

Error Not Found: /search/email_add/41/ while using script in ('search/') URL

Ajax Request

$.ajax({
                url: 'email_add/'+person_id+'/',
                method: 'POST',
                data: {
                    'email': email,
                },
                error: function(result){},
                success: function(result){},

urls.py

urlpatterns = [
    path('', views.contact_list, name="contact_list"), # GET
    path('add/', views.contact_add, name="contact_add"), # POST
    path('search/', views.contact_search, name="contact_search"), # GET
    path('delete/<int:pk>/',  views.contact_detail, name="contact_delete"), # DELETE
    path('edit/<int:pk>/',  views.contact_detail, name="contact_edit"), # POST
    path('phone_add/<int:pk>/', views.phone_add, name="phone_add"), # POST
    path('email_add/<int:pk>/', views.email_add, name="email_add"), # POST
    # path('search/phone_add/<int:pk>/', views.phone_add, name="phone_add_from_search"),
    # path('search/email_add/<int:pk>/', views.email_add, name="email_add_from_search"),

]

Within your javascript this url: 'email_add/'+person_id+'/' is accessing a relative url. So if you're in url http://my-web-site/some/path it will take you to http://my-web-site/some/path/email_add/id/

I think you want the http://my-web-site/email_add/id/ which means you need url: '/email_add/'+person_id+'/'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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