Axios无法从Django视图获取JSON [英] Axios unable to get JSON from Django view

查看:108
本文介绍了Axios无法从Django视图获取JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用axios和django视图实现前端和后端数据交互.现在,我已成功使用以下代码将数据发布到django视图.

I want to implement a front-end and back-end data interaction with axios and django view. Now I have succeed in posting data to django view with code below.

axios.post("{% url 'main:getCommodityInfo'%}",
                        param,
                        {headers:{'X-CSRFToken': this.getCookie('csrftoken')}})
                .then(response=>{
                  console.log(response);
                  alert("response has been caught");
                })
                .catch(error=>{
                  console.log(error);
                  alert("connection has error")
                })

但是当我想将json从视图返回到axios时:

But when I want to return json from view to axios:

def getCommodityInfo(request):
    if request.method=="POST":
        # get POST parameters
        searchKey = request.POST.get('searchKey')
        category = request.POST.get('category')
        print("Enter the POST view!  ", searchKey, category)
        # unique ID for each record for DB
        uniqueId = str(uuid4())
        # spider setting
        settings = {
            'unique_id': uniqueId,
            'USER_AGENT': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
        }
        # taskId to indentify each task
        task = scrapyd.schedule('JDSpider', 'getCommodityInfo',
                                settings=settings, searchKey=searchKey, category=category)

        print("It seems everything is running well? ")
        return JsonResponse({'taskId': task, 'uniqueId': uniqueId, 'status': 'started'},safe=False)

浏览器没有变化!首先,我试图弄清为什么它是独立发生的. 潜在的线索可能在于urls.py.

the browser has no change! Firstly, I tried to figure out why it occurred independently. The potential clue maybe lie in urls.py.

urlpatterns = [
    # eg:127.0.0.1:8000/main/
    path('', views.index, name = 'index'),
    path('getCommodityInfo/',views.getCommodityInfo, name = 'getCommodityInfo'),
    path('getCommodityCommentDetail/',views.getCommodityCommentDetail, name="getCommodityCommentDetail"),
    path('commodityInfo/<str:category>/<str:searchKey>/',views.commodityInfoPage, name = 'commodityInfoPage'),
    path('commentsInfo/<str:commodityId>/',views.commodityCommentPage,name = 'commodityCommentPage'),
    # path('?searchkey=<str:searchKey>&categroy=<str:category>/',views.getCommodityInfo, name = 'getCommodityInfo'),
]

因为我发现单击按钮以将数据发布到 getCommodityInfo 视图的按钮后,浏览器中的初始 url http://127.0.0.1:8000/main/变为http://127.0.0.1:8000/main/?searchKey=switch&category=Electronics.该网址似乎与 urls.py 中的任何网址格式都不匹配.因此,我尝试附加一个urlpattern path('?searchkey=<str:searchKey>&categroy=<str:category>/',views.getCommodityInfo, name = 'getCommodityInfo').不幸的是,它不起作用.

Because I found that the initial url http://127.0.0.1:8000/main/ in my browser after clicking on the button to post data to getCommodityInfo view became http://127.0.0.1:8000/main/?searchKey=switch&category=Electronics . This url seems not to match any url patterns in urls.py. So I tried to append an additional urlpattern path('?searchkey=<str:searchKey>&categroy=<str:category>/',views.getCommodityInfo, name = 'getCommodityInfo'). Unfortunately, it doesn't work.

之后,我在网上搜索了很长时间.但是没用.请告诉我我的解决方案是否正确.或尝试给出一些实现方法的想法.在此先感谢.

After that, I am searching for a long time on net. But no use. Please tell me whether my idea to solve right. Or try to give some ideas how to achieve this.Thanks in advance.

编辑1 询问我的控制台日志.

这是单击按钮发布数据后的控制台日志.

This is my console log after click the button to post data.

当我单击警报时,浏览器转到http://127.0.0.1:8000/main/?searchKey=switch&category=Electronics,Chrome网络加载如下所示:

And when I click on the alert, the browser go to http://127.0.0.1:8000/main/?searchKey=switch&category=Electronics and the chrome network loading shows like:

控制台中没有日志输出.

And there are no log output in console.

编辑2 对于axios是通过POST还是GET发送请求存在一些疑问,我尝试在django视图中对其进行识别

我的python控制台输出了此信息,这意味着 getCommodityInfo 确实将请求标识为POST(您可以查看我的代码)

My python console output this, meaning getCommodityInfo did indentify the request as POST(You could review my code)

编辑3 @dirkgroten指出我可能同时发送了POST和GET.因此,我在模板中提供了与之相关的整个代码

这是我的表格.与整个js相关.

And here is my form. And whole js related.

<form action="" id="searchForm">
<label for="searchKey">KeyWords</label>
<input v-model="searchKey" palceholder="Input Search Key" type="string" class="form-control" id="searchKey" name="searchKey">
<label for="category">Commodity Category</label>
<select v-model="selected" id="category" name="category">
    <option v-for="option in options" v-bind:value="option.value">
        ${option.text}
    </option>
</select>

<button v-on:click="startSpider"  class="btn btn-default" >Submit</button>
<p>KeyWords : ${ searchKey }</p>
<p>Category : ${ selected }</p>

</form>

<script type="text/javascript">
    var searchApp = new Vue({
        delimiters:['${','}'],
        el: "#searchForm",
        data:{
          searchKey:'',
          selected:'',
          options: [
            {text: 'Baby', value:'Baby'},
            {text: 'Book', value:'Book'},
            {text: 'Electronics', value:'Electronics'},
            {text: 'Fashion', value:'Fashion'},
            {text: 'Food', value:'Food'},
            {text: 'Health&Beauty', value:'Health&Beauty'},
            {text: 'Home', value:'Home'},
            {text: 'Industrial&Scientific', value:'Industrial&Scientific'},
            {text: 'Motor', value:'Motor'},
            {text: 'Pet', value:'Pet'},
            {text: 'Sports', value:'Sports'},
            {text: 'Other', value:'Other'},
          ]
        },
        created:function(){
          this.selected = "";
        },
        methods:{
          startSpider:function(event){
            console.log(this.searchKey);
            console.log(this.selected);
            alert("spider is ready to run!");
            var param = new URLSearchParams();
            param.append('searchKey',this.searchKey);
            param.append('category',this.selected);

            axios.post("{% url 'main:getCommodityInfo'%}",
                        param,
                        {headers:{'X-CSRFToken': this.getCookie('csrftoken')}})
                .then(response=>{
                  this.searchKey = "!!!";
                  this.category = "Baby";
                  console.log(response.data)
                  alert("response has been caught");
                  console.log(response.data)
                })
                .catch(error=>{
                  console.log(error);
                  alert("connection has error")
                })
          },
          getCookie:function(name) {
              var value = '; ' + document.cookie
              var parts = value.split('; ' + name + '=')
              if (parts.length === 2) return parts.pop().split(';').shift()
            },
        }
    });
</script>

推荐答案

完全,我发现了这个错误.全部与<form>有关...解决方案位于此处

Acutally, I have found the mistake. It's all about the <form>... The solution is here

这篇关于Axios无法从Django视图获取JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆