How to return ajax Response with python HTTPServer?

Viewed 308

I create a sample http server in python,and trying to connect it with ajax post method. when the client start post,I got connection ajax from:... log in my server and than send_response(200), but in my client part,there always got error and response['status'] = 0,please help me,very thanks!

HTTPServer part:(python)

class ajax_server(BaseHTTPRequestHandler):
    def do_POST(self):
        print('connection ajax from:', self.address_string())
        data={"data":"test"}
        json_string = json.dumps(data)
        self.send_response(200)
        self.send_header(
            'Content-type',
            'application/json'
        )
        self.end_headers()
        self.wfile.write(json_string.encode(encoding='utf-8'))
server = ThreadedHTTPServer("my server ip", ajax_server)
server.serve_forever()

Client part:(javascript)

    $(document).ready(function () {
        update_ajax();
        function update_ajax() {    
            $.ajax({
                url: "my server url",
                type: 'POST',
                success: function (response) {
                    alert(response["status"]);
                },
                error: function (response) {
                    alert(response['status']);
                }
            })
            //setTimeout(update_ajax, 1000);
        }  
    });

update:

  1. this server can past json data to chrome browser
  2. this client works well with django JsonResponse return (response['status'] = 200)

there must some mistake I ignore to create an ajax Response like django does.

1 Answers

finally,I found to add Access-Control in header and it works~

def do_POST(self):
    print('connection ajax from:', self.address_string())
    data={"data":"test","status":200}
    json_string = json.dumps(data)
    self.send_response(200)
    self.send_header("Content-type", "application/json") 
    self.send_header("Access-Control-Allow-Origin", "*") 
    self.send_header("Access-Control-Expose-Headers", "Access-Control-Allow-Origin") 
    self.send_header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept") 
    self.end_headers() 
    self.wfile.write(json_string.encode(encoding='utf-8'))
Related