django project simple retrieval of Baidu translation Interface

1, built routing;

2, writing method;

def fanyi(request):
    import requests
    import json
    content = request.POST.get('content')
    try:
        if not content:
            res={'status':1,'info':'未输入查询内容'}
            return HttpResponse(json.dumps(res))
        else:
            headers = {
                'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
            }
            parmas = {'kw': content}
            response = requests.post(url='https://fanyi.baidu.com/sug', params=parmas, headers=headers)
            print(json.loads(response.text)['data'][0]['v'])
            res={'status':0,'info':json.loads(response.text)[' Data ' ] [0] [ " V " ]}
             return the HttpResponse (json.dumps (RES))
     the except : 
        RES = { ' Status ' : 2, ' info ' : ' not to query results, the correct entry ' }
         return   the HttpResponse (json.dumps (RES))

3, the front page; form form submission;

<form method="post" onsubmit="return false" id="form">
          {% csrf_token %}
        <div>
            <button>英汉互译</button>
            <br>
            <textarea name="content" cols="50" rows="10" class="main"></textarea>
            <input type="button" id="onsubmit">div</>= "query"value
        
      </form>

4, triggering an event and return the results of a jquery;

<script>
    $('#onsubmit').click(function () {
        console.log(123);
        $.post('/apply/fanyi/',$('#form').serialize(),function (data) {
            if (data['status']==0){
                layer.alert(data['info'], {
                      skin: 'layui-layer-molv' //样式类名
                      , closeBtn and: 0 
                    }) 
            } the else { 
                layer.alert (Data [ ' info ' ], { 
                      icon: . 1 , 
                      Skin: ' Layer-EXT-Moon '  // . friendship extended from the skin on the skin layer.seaning.com extension rule, go here Now 
                    }) 
            } 
        }, ' JSON ' ) 
    }) 
</ Script >

5, page effect;

 

done

 

Guess you like

Origin www.cnblogs.com/nmsghgnv/p/11307120.html