簡體   English   中英

無法調用ajax / dajax方法

[英]Can't call ajax/dajax method

我正在編寫一個django應用程序,其中用戶想要單擊按鈕並進行部分頁面更改。 數據需要從服務器傳遞到網頁,而無需完全刷新頁面。 這個任務聽起來像ajax的工作。 但是,我無法在我的應用程序中使用Ajax。

我無法將調用轉到服務器端函數。 以下是主題與未接來電有關的代碼。 我的目的是讓服務器端返回未接來電列表,並顯示給用戶,而無需刷新頁面。

當我單擊該按鈕時,出現一個使用螢火蟲顯示“發生錯誤的消息”的彈出窗口,我將其追溯到DAJAXICE_EXCEPTION,但我對此一無所知。

這里發生了什么? 我該如何工作? 另外,如果有一種更簡單的方法不需要Dajax庫,請告知。 任何分步示例都將非常有幫助。

服務器端功能

-------- /jim/ajax.py---------

@dajaxice_register 
def missedCalls(request, user): 
    print "Ajax:missedCalls"    #never prints...
    missedCalls = ScheduledCall.objects.filter(status__exact='Missed') 
    render = render_to_string('examples/pagination_page.html', { 'missedCalls': missedCalls }) 
    dajax = Dajax() 
    dajax.assign('#calls','innerHTML', render) 
    return dajax.json() 

------- page.html中---------

 <script type='text/javascript'>
   function missed_calls_callback(data){
      # The dajax library wants a function as a return call.
      # Have no idea what I'm supposed to do with this part of the function.
      # what is supposed to go here?
      alert(data.message);
   }  
 </script>

 <!-- Button -->
 <input type="button" name="calltest" value="JQuery Test" 
    id="calltest" onclick="Dajaxice.jim.missedCalls(missed_calls_callback, {'user':{{ user }}})">


  <div id="calls">
     {% include "calls.html" %}
  </div>

-------- calls.html --------

<h2> Missed Calls</h2>
<ul>         
{% for i in missedCalls.object_list %}         
    <li>{{ i }}</li>
{% endfor %}     
</ul>  

在開始使用庫之前,如果需要手動進行操作(以查看發生了什么情況)可能會有所幫助。

ajax請求是HTTP請求,與其他請求一樣,除了異步發生(即在正常請求/響應周期之外)之外,它通常返回json或xml(盡管您可以根據需要返回html)。

這意味着要接受AJAX請求,您只需像通常那樣創建一個URL並查看即可。

urls.py

...
url(r"^/my/ajax/path/$", myapp.views.ajax_view, name="do-something-ajaxy"),
...

views.py

def ajax_view(self, request):
    # Django's Request objects have a method is_ajax()* 
    # which checks the header to see if it's an 'ajax' request
    if request.is_ajax():
        raise Http404
    missedCalls = ScheduledCall.objects.filter(status__exact='Missed') 
    # You can return a dictionary-like json object which can be manipulated by the javascript when it receives it
    return HttpResponse(simplejson.dumps(missedCalls), mimetype='application/javascript')

https://docs.djangoproject.com/zh-CN/dev/ref/request-response/#django.http.HttpRequest.is_ajax

並使用jquery執行ajax請求:

(function($){
    $.ajax({
        type: 'GET',
        url: '/my/ajax/path/',
        success: function(data){
            for call in data:
                /* Do something with each missed call */
        },
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM