gpt4 book ai didi

通过 AJAX 将 Javascript POST 发送到 Django 根本无法正常工作

转载 作者:行者123 更新时间:2023-11-30 18:06:15 25 4
gpt4 key购买 nike

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

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

最佳答案

您没有从 Javascript submit 函数返回 false。这意味着 Ajax 被触发,但在它有机会做任何事情之前,按钮的默认操作发生并且表单正常提交,这就是 is_ajax 函数返回 false 的原因。如果 JS 返回 false,则不会触发该操作。

关于通过 AJAX 将 Javascript POST 发送到 Django 根本无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15747336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com