How do I integrate Ajax with Django applications?

前端 未结 8 585
忘了有多久
忘了有多久 2020-11-22 06:16

I am new to Django and pretty new to Ajax. I am working on a project where I need to integrate the two. I believe that I understand the principles behind them both, but have

8条回答
  •  日久生厌
    2020-11-22 06:42

    When we use Django:

    Server ===> Client(Browser)   
          Send a page
    
    When you click button and send the form,
    ----------------------------
    Server <=== Client(Browser)  
          Give data back. (data in form will be lost)
    Server ===> Client(Browser)  
          Send a page after doing sth with these data
    ----------------------------
    

    If you want to keep old data, you can do it without Ajax. (Page will be refreshed)

    Server ===> Client(Browser)   
          Send a page
    Server <=== Client(Browser)  
          Give data back. (data in form will be lost)
    Server ===> Client(Browser)  
          1. Send a page after doing sth with data
          2. Insert data into form and make it like before. 
          After these thing, server will send a html page to client. It means that server do more work, however, the way to work is same.
    

    Or you can do with Ajax (Page will be not refreshed)

    --------------------------
     
    Server ===> Client(Browser) [from URL1]    
          Give a page                      
    --------------------------  
    
    Server <=== Client(Browser)     
          Give data struct back but not to refresh the page.
    Server ===> Client(Browser) [from URL2] 
          Give a data struct(such as JSON)
    ---------------------------------
    

    If you use Ajax, you must do these:

    1. Initial a HTML page using URL1 (we usually initial page by Django template). And then server send client a html page.
    2. Use Ajax to communicate with server using URL2. And then server send client a data struct.

    Django is different from Ajax. The reason for this is as follows:

    • The thing return to client is different. The case of Django is HTML page. The case of Ajax is data struct. 
    • Django is good at creating something, but it only can create once, it cannot change anything. Django is like anime, consist of many picture. By contrast, Ajax is not good at creating sth but good at change sth in exist html page.

    In my opinion, if you would like to use ajax everywhere. when you need to initial a page with data at first, you can use Django with Ajax. But in some case, you just need a static page without anything from server, you need not use Django template.

    If you don't think Ajax is the best practice. you can use Django template to do everything, like anime.

    (My English is not good)

提交回复
热议问题