简体   繁体   English

如何将数据从 JavaScript 发送到 Python

[英]How to send data from JavaScript to Python

I am using GAE for web development, on jinja2 and python2.7我在 jinja2 和 python2.7 上使用 GAE 进行 Web 开发

I can get data from Python.我可以从 Python 获取数据。 But I failed to send data from JavaScript to Python.但是我无法将数据从 JavaScript 发送到 Python。 Here is the JavaScript code:这是 JavaScript 代码:

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):以及 Python 代码(main.py 中的 User_update 类):

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?如何从 Python 获取 JavaScript 数据?

HTTP Methods HTTP 方法

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 ). HTTP 有多种方法,例如 GET 和 POST(请参阅https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol )。

Relevant methods for you in this case:在这种情况下,您的相关方法:

  • GET is meant for read-only requests. GET用于只读请求。 Unlike other HTTP methods, GET requests do not carry body with data that is sent to the server.与其他 HTTP 方法不同,GET 请求不携带带有发送到服务器的数据的正文。 All of the data would get sent via URL parameters.所有数据都将通过 URL 参数发送。 In some case also as part of the header.在某些情况下也作为标题的一部分。 GET requests may be repeated or cached as they are read-only. GET 请求可能会重复或缓存,因为它们是只读的。 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. POSTPUT可以更新数据,一般POST用于创建对象,而PUT用于更新现有对象。 Both HTTP methods do accept a body with the data.这两种 HTTP 方法都接受带有数据的主体。

Since you are updating a user, PUT seems to be appropriate.由于您正在更新用户,因此PUT似乎是合适的。

Sending data to the server, via jQuery's ajax通过 jQuery 的 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.大多数开发人员可能会假设它,但列出所有直接依赖项是值得的,在这种情况下,您似乎正在使用 jQuery 来获取值并将请求发送到服务器。 In particular $.ajax : http://api.jquery.com/jQuery.ajax/特别是$.ajaxhttp : //api.jquery.com/jQuery.ajax/

As the documentation for the data attribute:作为data属性的文档:

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.它附加到 GET 请求的 url。

So even though GET doesn't accept a body, jQuery adds it to the URL for you.因此,即使GET不接受正文,jQuery 也会为您将其添加到 URL 中。 As mentioned before I would advice against using GET for updates.如前所述,我建议不要使用GET进行更新。

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我相信您使用的 API 是: 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 ):对于PUTPOST,它应该像这样工作( 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您的服务器代码容易受到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您应该使用 POST 而不是 GET 将数据发送到服务器

$.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然后在 Python 服务器中处理传入的数据

def post(self):
    ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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