简体   繁体   中英

How to send data from JavaScript to Python

I am using GAE for web development, on jinja2 and python2.7

I can get data from Python. But I failed to send data from JavaScript to Python. Here is the JavaScript code:

function toSave() {
    var val_no = $('#field-no').val();
    var val_name = $('#field-name').val();
    var val_address = $('#field-address').val();
    var val_phone = $('#field-phone').val();
    var val_car = $('#field-car').val();
    var val_penalty = $('#field-penalty').val();

    $.ajax({
        type: 'GET',
        url: "https:/test/User_update",
        data: {
            "no": val_no,
            "name": val_name,
            "address": val_address,
            "phone": val_phone,
            "car": val_car,
            "penalty": val_penalty
        },
        dataType: "json"
    }).done(function () {
        $('#modal-1').modal('hide');
        table.row.data([val_no, val_name, val_address, val_phone, val_car, val_penalty, UserIndex_CreateEditButton(val_no, val_name, val_address, val_phone, val_car, val_penalty), UserIndex_CreateDeleteButton(val_no)], $('#' + tempUpdate));
    });
}

And the Python code (class User_update in main.py):

import os
import webapp2
import MySQLdb
import json
import logging
import googlemaps
import jinja2
import sys
import urllib
import urllib2
import json as simplejson
import codecs

reload(sys)
sys.setdefaultencoding('utf-8')
from operator import eq
from datetime import datetime
from collections import OrderedDict

class User_update(webapp2.RequestHandler):
def get(self):

    jsonData = json.loads(self.get('data'))

#   penalty = self.request.get('data')

#   phone = urllib.request.urlopen(req).read() 
#   data = urllib.requset.urlopen("http://www.daum.net").read()
#   phone=urllib2.urlopen("https://firststep-2016.appspot.com/Log").read()  

    self.response.headers['Content-Type']='text/plain'

    db = connect_to_cloudsql()
    cursor = db.cursor()
    cursor.execute("SET names utf8")
    cursor.execute('SET SQL_SAFE_UPDATES=0;')
    cursor.execute("""update User set name='%s',address='%s',phone='%s',car_num='%s',penalty='%s' where no='%s' """%(jsonData.name,jsonData.address,jsonData.phone,jsonData.car,jsonData.penalty,jsonData.no))
    db.commit()
    db.close()

How can I get the JavaScript data from Python?

HTTP Methods

First it is good to understand how the communication works in general.

HTTP has various methods, such as GET and POST (see https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol ).

Relevant methods for you in this case:

  • GET is meant for read-only requests. Unlike other HTTP methods, GET requests do not carry body with data that is sent to the server. All of the data would get sent via URL parameters. In some case also as part of the header. GET requests may be repeated or cached as they are read-only. Which is why they shouldn't be used for updates.

  • POST and PUT can update data, generally POST is used to create objects whereas PUT is used to update an existing object. Both HTTP methods do accept a body with the data.

Since you are updating a user, PUT seems to be appropriate.

Sending data to the server, via jQuery's ajax

Most developers might assume it but it is worth listing out all of the direct dependencies, in this case you seem to be using jQuery to get the value and send the request to the server. In particular $.ajax : http://api.jquery.com/jQuery.ajax/

As the documentation for the data attribute:

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests.

So even though GET doesn't accept a body, jQuery adds it to the URL for you. As mentioned before I would advice against using GET for updates.

At this point you could make use of the browser's developer tools to inspect the network requests. That way you will see what exactly is sent to the server.

Receiving data in the server

I believe the API you are using is: http://webapp2.readthedocs.io/en/latest/guide/handlers.html

You should be able to get the individual values like so (there won't be a 'data' parameter):

val_no = self.request.get("no")
val_name = self.request.get("name")
# ...

For PUT or POST it should work like this ( http://webapp2.readthedocs.io/en/latest/guide/request.html#post-data ):

val_no = self.request.POST['no']
val_name = self.request.POST['name']
# ...

Security

Your server code is vulnerable to https://en.wikipedia.org/wiki/SQL_injection

It is not part of your question but quite serious. I wouldn't make that code available on a public server and if it is now I would remove it until fixed.

Looks like you are trying to post data using the wrong method. You should use POST instead of GET to send data to the server

$.ajax({
    type: 'POST',
    url: "https://firststep-2016.appspot.com/User_update",
    data: {
        "no": val_no,
        "name": val_name,
        "address": val_address,
        "phone": val_phone,
        "car": val_car,
        "penalty": val_penalty
    },
    dataType: "json"
}).done(function () {
    $('#modal-1').modal('hide');
    table.row.data([val_no, val_name, val_address, val_phone, val_car, val_penalty, UserIndex_CreateEditButton(val_no, val_name, val_address, val_phone, val_car, val_penalty), UserIndex_CreateDeleteButton(val_no)], $('#' + tempUpdate));
});

Then handle the incoming data in the Python server

def post(self):
    ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM