1

こんにちは、JavaScript 文字列変数を Django ビューに投稿しようとしています。とても簡単そうに見えますが、これをやり始めてから 3 日が経ちました。スタックオーバーフローに関するすべての関連する質問を実際に読んだことがありますが、何が間違っているのかわかりません..

テンプレート HTML ページの JAVASCRIPT

<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>

<!--also have a jquery file imported further up in my code - 
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
should be where it is getting ajax from, right?-->

<script language="JavaScript">
  $(function() {
  $( "#sortable" ).sortable();
  $( "#sortable" ).disableSelection();
  });

$(document).ready(function() {
$('#makeconstruct').submit(function()

{
        //Serializes the sortable's item id's into an array of string
        var senderStrIndexArray = $('#sortable').sortable();

    var linkOrder = $(senderStrIndexArray).sortable('toArray');
    alert(linkOrder);


    $.ajax({
        type: "POST",
        url: "/ecosystem/ajaxmes/",
        // The key needs to match your method's input parameter (case-sensitive).
        data: JSON.stringify({ linkOrder:linkOrder }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        //do we need json??
        success: function(data){alert(data);},
        failure: function(errMsg) {
            alert(errMsg);
        }
    });             
});
});
</script>

テンプレート上の HTML

<form id="makeconstruct" action="/ecosystem/ajaxmes/" method="post">
<!--DO WE NEED A METHOD/ACTION HERE IF IT IS DEFINED IN THE JAVASCRIPT??-->
{% csrf_token %}<!--view defined as csrf exempt but kept just in case-->
<ul id="sortable">
and a jQuery sortable list of things goes here in the code, each with an id
</ul>
<button type="submit">Submit</button></form>

VIEWS.PY

from django.utils import simplejson #not sure this is necessary given the code
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def ajaxmes(request):
    if request.is_ajax():
        message = "Yes, I am the king!!!"
    else:
        message = "No, I am going to cry!!"
    return HttpResponse(message)

URLS.PY

url(r'^ecosystem/ajaxmes', 'container.views.ajaxmes'),
#Think this is the only line I need to show here

javascript linkOrder 変数のアラートは機能しますが、「いいえ、泣くつもりです」という応答しか得られません。私たちは今、本当に必死です。助けてくれてありがとう。

4

2 に答える 2

2

submitJavascript関数から false を返していません。つまり、Ajax が起動されますが、何かを実行する前に、ボタンの既定のアクションが実行され、フォームが正常に送信されます。これが、is_ajax 関数が false を返す理由です。JS が false を返す場合、アクションは起動されません。

于 2013-04-01T17:08:16.020 に答える
0

url(r'^ecosystem/ajaxmes', 'container.views.ajaxmes')これをこれに変更してみてくださいurl(r'^ecosystem/ajaxmes/', 'container.views.ajaxmes'),

「/ecosystem/ajaxmes/」にリクエストを送信していますが、urls.py には末尾のスラッシュがないため、リダイレクトされています。

于 2013-04-01T16:39:15.703 に答える