嗨,我们只是想将一个 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 变量的警报有效,但我们得到的只是“不,我要哭了”响应。我们现在真的很绝望,在此先感谢您的帮助。