jquery ajax, django的sample

通过ajax向django发请求

代码片段

$("#id_article_1_load_button, #id_article_2_load_button, #id_article_3_load_button, #id_article_4_load_button").click(function() {
      id_array = this.id.split("_");
      link_name = id_array[1] + id_array[2];
      var article_id = $(this).siblings('input').val();
      var loader = $(this).parents('.form-row').next().find('textarea');
      $.get('/newsletter/newsletter_article/',{'article': article_id, 'link_name': link_name}, function(data){
        loader.val(data.content);  
      });
    });

urls

<table width="680" border="0" align="center" cellpadding="4" cellspacing="0">
  <tr>
    <td bgcolor="#FFFFFF" style="padding: 0 20px">
      <table width="100%" border="0" cellspacing="0" cellpadding="5">
        <tr>
          <td width="45%" height="301" valign="top">
            <p>
              <span style="font-family: Helvetica, Arial, sans-serif; font-size: 21px; color: #585d63; font-weight:bold; letter-spacing: -1px;">
                <br />
                {{ article.title }}
                <br />
                <span style="color: #3da0c4">Feature</span>
              </span>
            </p>
            <p>{{ article.subtitle|striptags|safe }}</p>
            <p><a class="detail_link" href="http://www.shanghaiexpat.com{{ article.get_absolute_url }}" target="_blank">READ MORE</a></p>
          </td>
          <td width="50%" align="center" valign="top">
            <p>
              <span style="font-family: Helvetica, Arial, sans-serif; font-size: 22px; color: #585d63; font-weight:bold; letter-spacing: -1px;">
                <a name="{{ link_name }}" id="angkor5"></a>
              </span>
              <br />
              <br />
	  {% with article.pic as image %}
	  <img src="http://www.shanghaiexpat.com{{ image.url }}" width="285" height="193" border="0" alt="thumb190-2" />
	  {% endwith %}
            </p>
            <p><span class="photo">Photo description goes here</span></p>
          </td>
        </tr>
      </table>
    </td>
  </tr>
</table>

views

def newsletter_article(request):
    article_id = request.GET.get('article', None)
    link_name = request.GET.get('link_name', None)
    if article_id is None:
        raise Http404
    article = get_object_or_404(Article, pk=article_id)
    host = "http://%s" % request.get_host()
    tpl = select_template(['admin/newsletter/fragments/article.html',])
    content = tpl.render(RequestContext(request, locals()))
    return JSONResponse({'content': content})

相关推荐