python给js变量赋值,在Python和Javascript之间传递变量

Imagine that you need to write some Javascript that simply changes a set of checkboxes when a drop down list is changed.

Depending on which item is selected in the list, some of the checkboxes will become checked/unchecked.

In the back, you have Python code along with some SQLAlchemy.

The Javascript needs to identify the selected item in the list as usual, send it back to the Python module which will then use the variable in some SQLAlchemy to return a list of checkboxes which need to be checked i.e. "User selected 'Ford', so checkboxes 'Focus', 'Mondeo', 'Fiesta' need to be checked"

The issue Im having is that I cant seem to find a way to access the python modules from the Javascript without turning a div into a mini browser page and passing a url containing variables into it!

Does anyone have any ideas on how this should work?

解决方案

Funny, I've got web pages with JavaScript that talk to Python CGI modules that use SQLAlchemy.

What I do is send AJAX request but with JSON request in the body instead of XML. Python CGI modules use standard json module to deserialize JSON into a dictionary.

JavaScript side looks like this:

function on_request_success(response) {

console.debug('response', response);

}

function on_request_error(r, text_status, error_thrown) {

console.debug('error', text_status + ", " + error_thrown + ":\n" + r.responseText);

}

var request = { ... };

jQuery.ajax({

url: 'http://host/whatever.cgi',

type: 'POST',

cache: false,

data: JSON.stringify(request),

contentType: 'application/json',

processData: false,

success: on_request_success,

error: on_request_error

});

And Python like this:

request = json.load(sys.stdin)

response = handle_request(request)

print("Content-Type: application/json", end="\n\n")

json.dump(response, sys.stdout, indent=2)

Note, it doesn't use Python cgi module, since the whole request is passed as JSON in the body.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值