1

嗨,我们只是想将一个 javascript 字符串变量发布到 django 视图。这听起来很容易,但自从我开始尝试这样做已经三天了!我实际上已经阅读了有关堆栈溢出的所有相关问题,但我只是不知道我做错了什么..

模板 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>

意见.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

您没有从 Javascriptsubmit函数返回 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 回答