使用Python从JS调用Ajax

时间:2017-07-28 16:16:26

标签: javascript jquery python ajax django

我有简单的django项目名称 Ajax 。我只为此项目名称 Promocode 安装了一个应用程序。 我在这个项目中的问题是js和python之间的Ajax调用。我无法使用ajax调用函数处理 Succes 。错误:我得到的function()结果。  我知道我错误地在promocode应用程序中的urls.py和ajax调用函数中的url映射但我无法解决这个问题。请帮帮我:)。

我的主要urls.py文件是:

from datetime import datetime
from django.conf.urls import url,include
import django.contrib.auth.views

urlpatterns = [
   url(r'^', include('promocode.urls'))]

我的promocode app urls.py文件是:

from django.conf.urls import url, include
from . import views

urlpatterns = [
       url(r'^$', views.index,name='index'),
       url(r'^$', views.extract_json)]

我的views.py文件是:

from django.shortcuts import render
import json
from suds.client import Client as Client
from django.http.response import HttpResponse


def index(request):
    return render(request,'promocode/index.html')


def get_result_by_code(promocode):
    url = "http://service.emobile.az:8080/ws-loyalty-
    program/cp/loyaltyprogram.wsdl"
    client = Client(url)
    result = client.service.loyaltyProgramCalculate(
         amount=1000,
         authKey='testaede35740f2b9d2248b0ab6b878',
         identicalCode=promocode,
         terminalCode=2148)
    if str(result[2]) == "SUCCESS":
        status = 1
    else:
        status = 0
    return status


def extract_json(request):
    data = json.loads(request.body)
    status = get_result_by_code(data['4545'])
    result = dict(
       status=status,
       message='Result Succesfully'
    )
    return HttpResponse(json.dumps(result), mimetype='application/json')

我的index.html文件是:

<!DOCTYPE html>
<html>
<head>
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
</head>
<body>

<h3>Promocode Test </h3>

<label for="bakcelPromo">Promocode</label> <br>
<input type="text" name="bakcelPromo" id="bakcelPromo" class="form-control">
<br>
<br>
<label for="sum">Sum Insured</label> <br>
<input type="text" name="sum" id="sum" value="" class="form-control">

<p></p>

<button onclick="get_result_by_code();">Hesabla</button>

<br>
<br>
<label for="premium">Premium</label> <br>
<input id="premium" type="text" />
<br>
<br>

<script>
function get_result_by_code() {
var sum_insured = document.getElementById("sum").value * 0.035;
var promocode = document.getElementById("bakcelPromo").value;

$.ajax({
    type: "GET",
    url: "promocode/" ,
    dataType: "json",
    async: true,
    data: { "promocode": promocode },
    success: function (response) {
        if (response.status == 1) {
            sum_insured = sum_insured * 0.8

        } else {
            sum_insured = sum_insured * 1.5
            }
        $('#output').html(response.message);

        },
        error: function () {
            alert('There was an error communicating with the server.');
        }
});
document.getElementById("premium").value = parseInt(sum_insured);
}  
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

我的主要urls.py文件是:

from datetime import datetime
from django.conf.urls import url,include
import django.contrib.auth.views

urlpatterns = [
   url(r'^', include('promocode.urls'), namespace='appname')]

我的promocode app urls.py文件是:

from django.conf.urls import url, include
from . import views

urlpatterns = [
       url(r'^$', views.index,name='index'),
       url(r'^promo/$', views.extract_json, name='extract_json')]

我的views.py文件是:

from django.shortcuts import render
import json
from suds.client import Client as Client
from django.http.response import HttpResponse


def index(request):
    return render(request,'promocode/index.html')


def get_result_by_code(promocode):
    url = "http://service.emobile.az:8080/ws-loyalty-
    program/cp/loyaltyprogram.wsdl"
    client = Client(url)
    result = client.service.loyaltyProgramCalculate(
         amount=1000,
         authKey='testaede35740f2b9d2248b0ab6b878',
         identicalCode=promocode,
         terminalCode=2148)
    if str(result[2]) == "SUCCESS":
        status = 1
    else:
        status = 0
    return status


def extract_json(request):
    if request.is_ajax():
        promocode = request.POST.get("promocode")
        status = get_result_by_code(promocode)
        result = dict(
           status=status,
           message='Result Succesfully'
        )
        return HttpResponse(json.dumps(result), mimetype='application/json')

我的index.html文件是:

<!DOCTYPE html>
<html>
<head>
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
</head>
<body>

<h3>Promocode Test </h3>

<label for="bakcelPromo">Promocode</label> <br>
<input type="text" name="bakcelPromo" id="bakcelPromo" class="form-control">
<br>
<br>
<label for="sum">Sum Insured</label> <br>
<input type="text" name="sum" id="sum" value="" class="form-control">

<p></p>

<button onclick="get_result_by_code();">Hesabla</button>

<br>
<br>
<label for="premium">Premium</label> <br>
<input id="premium" type="text" />
<br>
<br>

<script>
function get_result_by_code() {
var sum_insured = document.getElementById("sum").value * 0.035;
var promocode = document.getElementById("bakcelPromo").value;

$.ajax({
    method: "POST",
    url: "{% url "appname:extract_json" %}" ,
    async: true,
    data: { "promocode": promocode },
    success: function (response) {
        if (response.status == 1) {
            sum_insured = sum_insured * 0.8

        } else {
            sum_insured = sum_insured * 1.5
            }
        $('#output').html(response.message);

        },
        error: function () {
            alert('There was an error communicating with the server.');
        }
});
document.getElementById("premium").value = parseInt(sum_insured);
}  
</script>
</body>
</html>