如何将数据从JavaScript发送到Python [英] How to send data from JavaScript to Python

查看:190
本文介绍了如何将数据从JavaScript发送到Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在jinja2和python2.7上使用GAE进行Web开发

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

我可以从Python获取数据.但是我无法将数据从JavaScript发送到Python.这是JavaScript代码:

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

以及Python代码(main.py中的User_update类):

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()

如何从Python获取JavaScript数据?

How can I get the JavaScript data from Python?

推荐答案

HTTP方法

首先,最好了解一下交流的总体工作原理.

HTTP Methods

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

HTTP具有多种方法,例如GET和POST(请参阅 https://en.wikipedia.org /wiki/Hypertext_Transfer_Protocol ).

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 用于只读请求.与其他HTTP方法不同,GET请求不携带发送到服务器的数据.所有数据都将通过URL参数发送.在某些情况下,还作为标头的一部分. GET请求可以是重复的,也可以是只读的,可以将其缓存.这就是为什么不应将它们用于更新的原因.

  • 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 PUT 可以更新数据,通常 POST 用于创建对象,而 PUT 用于更新现有对象.这两种HTTP方法都接受带有数据的正文.

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.

由于您要更新用户,因此 PUT 似乎是合适的.

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

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

作为data属性的文档:

要发送到服务器的数据.如果还不是字符串,则将其转换为查询字符串.它被附加到GET请求的URL上.

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 不接受正文,jQuery也会将其添加到您的URL中.如前所述,我建议不要使用 GET 进行更新.

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.

我相信您使用的API是: http://webapp2.阅读thedocs.io/en/latest/guide/handlers.html

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")
# ...

对于 PUT POST ,它应该像这样工作(

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']
# ...

安全性

您的服务器代码容易受到 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.

这篇关于如何将数据从JavaScript发送到Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆