jQuery + Python响应数据

The following jQuery will call a Python script. The Python script is able to receive the post data. However, the jQuery is unable to receive the response by the Python script.

$(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);
    });
  });
});

The following is the python script:

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

In Django, printing things does not send them back to the client; you need to actually return a response. See the Django tutorial part 3:

from django.http import HttpResponse

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

I have found the solution.

$(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);
    });
  });
});

The returned variable in the Python script needs to have the same variable name.

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