2013-12-23 28 views
1

以下jQuery將調用Python腳本。 Python腳本能夠接收發布數據。但是,jQuery無法通過Python腳本接收響應。jQuery + Python響應數據

$(document).ready(function(){ 
    $("#dd").blur(function(){ 
    $.post("http://127.0.0.1:8000/validation/trial/", 
    { 
     dd:document.getElementById("dd").value 
    }, 
    function(data){ 
     alert("Data: " + data); 
    }); 
    }); 
}); 

以下是python腳本:

def trial(request): 
    dd = request.POST.get('dd') 
    print dd 
    return HttpResponse(dd) 
+0

您必須返回您的值才能將其發送給JQuery –

+0

我使用了HttpResponse,但它不起作用。 – ezekieltanch

+0

你剛剛嘗試過直接返回嗎? –

回答

1

在Django中,print ING事情不把他們送回給客戶端;你需要實際返回一個響應。請參閱the Django tutorial part 3

from django.http import HttpResponse 

def index(request): 
    return HttpResponse("Hello, world. You're at the polls index.") 
+0

沒有。不起作用。 – ezekieltanch

+0

請更新您的問題與您的新代碼(請顯示您的整個看法) – sk1p

+0

更新我的問題。 – ezekieltanch

0

我找到了解決方案。

$(document).ready(function(){ 
    $("#dd").blur(function(){ 
    $.post("http://127.0.0.1:8000/validation/trial/", 
    { 
     dd:document.getElementById("dd").value 
    }, 
    function(data){ // <-- note that the variable name is "data" 
     alert("Data: " + data); 
    }); 
    }); 
}); 

Python腳本中的返回變量需要具有相同的變量名稱。

def trial(request): 
    data = request.POST.get('dd') 
    return HttpResponse(data)