【问题标题】:Django form post(AJAX) direct to somewhere elseDjango表单发布(AJAX)直接到其他地方
【发布时间】:2018-03-12 11:58:09
【问题描述】:

我知道我的问题很模糊,也被问了很多次(但我无法理解任何解决方案)。我想去的是 url search_res/save_tweet 并从模板 show_tweets.html 传递数据使用 AJAX 的 json 格式。

我认为我的 ajax 无法正常工作。当我按下按钮时,它会转到某个地方http://127.0.0.1:8000/search_res/?

我是 django 和 ajax 的新手。

show_tweets.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tweets Result</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        save_tweets = function(tweet_id,created_at,text,lang){
            alert(tweet_id,created_at,text,lang);
            $.ajax({
                type : 'POST',
                url : '/search_res/save_tweet/',
                dataType : 'json',
                data: {
                    'tweet_id' : tweet_id,
                    'created_at' : created_at,
                    'text' : text,
                    'lang' : lang
                },
                success: function(data) {
                    alert(data);
                }
            });

        }

    </script>
</head>
<body>
<h1 align="center">Tweets Results</h1>
<ul>
    {% for k,v in json_d %}
        <div>
            {{ k }} : {{ v.full_text }}
            <form onsubmit="save_tweets('{{ v.id_str }} , {{ v.created_at }} , {{ v.full_text }} , {{ v.lang }}')">{% csrf_token %}
                <input type="submit" value="Toxic"/>
            </form>
        </div>
    {% endfor %}
</ul>


</body>
</html>

views.py

def show_tweets(request):
if request.GET['hashtag'] and request.GET['user']:
    template = loader.get_template('error.html')
    return HttpResponse(template.render({},request))
else:
    if request.GET['hashtag']:
        hashtag= request.GET['hashtag']
        try: all_tweets = tweepy.Cursor(api.search, q=hashtag + ' -filter:retweets', tweet_mode='extended').items(100)
        except: print("error")
        d = {}
        cnt = 0
        for t in all_tweets:
            cnt += 1
            d['Tweet_' + str(cnt)] = t._json
        dump_d = json.dumps(d)
        json_d = json.loads(dump_d)
    else:
        user = request.GET['user']
        try: all_tweets = api.user_timeline(screen_name=user, count=100, include_rts=True, tweet_mode='extended')
        except: print("error")
        d = {}
        cnt = 0
        for t in all_tweets:
            cnt += 1
            d['Tweet_' + str(cnt)] = t._json
        dump_d = json.dumps(d)
        json_d = json.loads(dump_d)
    context = {'json_d': json_d.items()}
    return render(request,'show_tweets.html',context)

def save_tweet(request):
    data = request.POST.get('tweet_id')
    print(data);
    #tweets(Text = data).save()
    return render(request,'success.html')

urls.py

urlpatterns = [
    url(r'^$', views.index,name='index'),
    url(r'^search_res/$', views.show_tweets,name='show_tweets'),
    url(r'^search_res/save_tweet/$', views.save_tweet,name='save_tweet')
]

【问题讨论】:

    标签: ajax django django-forms


    【解决方案1】:

    我唯一注意到的是您正在使用的 save_tweet 函数中的 views.py

     data = request.GET.get('tweet_id')
    

    但是,既然您要发布您的数据,您应该使用

     data = request.POST.get('tweet_id')
    

    编辑: 在阅读了澄清您想要什么的评论后,您似乎正在使用 AJAX,而您更愿意使用标准表单操作。所以您的代码看起来像:

    <form action="/search_res/save_tweet/" method="post" id="form">
        <input type="hidden" value="{{ v.id_str }}"/>
        <input type="hidden" value="{{ v.created_at }}"/>
        <input type="hidden" value="{{ v.full_text }}"/>
        <input type="hidden" value="{{ v.lang }}"/>
     </form>
    

    或者您可以让您的 views.py 文件中的 save_tweet 函数返回成功消息并在 Ajax 成功函数中处理成功:

    views.py

    def save_tweet(request):
        data = request.POST.get('tweet_id')
        print(data);
        #tweets(Text = data).save()
        return HttpResponse(json.dumps({"data":data}), status=200,content_type="application/json")
    

    show_tweets.html

     $.ajax({
                type : 'POST',
                url : '/search_res/save_tweet/',
                dataType : 'json',
                data: {
                    'tweet_id' : tweet_id,
                    'created_at' : created_at,
                    'text' : text,
                    'lang' : lang
                },
                success: function(data, textStatus,jqXHR) {
                    if(jqXHR.status === 200) {
                        window.location.replace('success.html')
                    }
                }
            });
    

    【讨论】:

    • 没关系..我希望页面将我重定向到127.0.0.1:8000/search_res/save_tweets而不是127.0.0.1:8000/search_res/?
    猜你喜欢
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 2012-02-19
    • 1970-01-01
    相关资源
    最近更新 更多