有没有办法使用JavaScript保证在所有情况下都可以使用?
我详细说明.常见的方法似乎是:
formElement.submit()
Run Code Online (Sandbox Code Playgroud)
这一切都很好,除了一件事.表单的字段可用作属性formElement,因此如果存在名称或标识为 "text1" 的字段,则可以将其作为formElement.text1.
这意味着如果一个元素被称为"提交"(无论是它的名字还是它的id),那么formElement.submit()它将不起作用.这是因为formElement.submit不是表单的方法,而是具有该名称的字段.不幸的是,提交按钮具有"提交"名称或ID是相当普遍的.
两个例子来说明我的观点.首先,以下内容不起作用,因为表单的元素名称为"submit":
<form name="example" id="example" action="/">
<button type="button" name="submit" onclick="document.example.submit(); return false;">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
以下将工作.唯一的区别是我从表单中删除了名称"submit":
<form name="example" id="example" action="/">
<button type="button" onclick="document.example.submit(); return false;">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
那么,还有其他方法可以使用JavaScript提交HTML表单吗?
上下文:应用程序使用必须在config.ru中设置的Rack中间件,而不是Rails的内部中间件链.这是出于与此问题无关的原因.
问题:如何让我的测试(功能和集成)了解这个中间件?
我会举一个例子来说明问题.让我们创建一个原始的Rails 3应用程序,使用机架重写进行说明.
# /config/initializers/example.rb
Rails.application.middleware.insert 0, 'Rack::Rewrite' do
r301 '/so', 'http://stackoverflow.com'
end
# /test/integration/the_test.rb
require 'test_helper'
class TheTest < ActionDispatch::IntegrationTest
test "redirect from /so to http://stackoverflow.com" do
get '/so'
assert_redirected_to 'http://stackoverflow.com'
end
end
Run Code Online (Sandbox Code Playgroud)
如果您运行上述测试,一切都很好,使用浏览器,您可以确认访问路径/so会将您重定向到StackOverflow.
很酷,让我们现在在Rails之外设置它.删除上述文件/config/initializers/example.rb,并更改config.ru为以下内容:
# /config.ru
require ::File.expand_path('../config/environment', __FILE__)
map '/so' do
run Rack::Rewrite do
r301 '', 'http://stackoverflow.com'
end
end
map '/' do
run Deleteme::Application
end
Run Code Online (Sandbox Code Playgroud)
现在,测试将停止工作.如果您/so使用浏览器访问,该功能确实有效.只是测试不知道Rack设置.
如何在Python中获取多维字典的URL编码版本?不幸的是,urllib.urlencode()只能在一个维度上工作.我需要一个能够递归编码字典的版本.
例如,如果我有以下字典:
{'a': 'b', 'c': {'d': 'e'}}
Run Code Online (Sandbox Code Playgroud)
我想获取以下字符串:
a=b&c[d]=e
Run Code Online (Sandbox Code Playgroud) 以下代码检查了float()在输入非ascii符号时方法的行为:
import sys
try:
float(u'\xbd')
except ValueError as e:
print sys.getdefaultencoding() # in my system, this is 'ascii'
print e[0].decode('latin-1') # u'invalid literal for float(): ' followed by the 1/2 (one half) character
print unicode(e[0]) # raises "UnicodeDecodeError: 'ascii' codec can't decode byte 0xbd in position 29: ordinal not in range(128)"
Run Code Online (Sandbox Code Playgroud)
我的问题:为什么错误信息e[0]以Latin-1编码?默认编码是Ascii,这似乎是unicode()预期的.
平台是Ubuntu 9.04,Python 2.6.2
python ×2
encoding ×1
exception ×1
forms ×1
html ×1
integration ×1
javascript ×1
python-2.x ×1
rack ×1
testing ×1
urlencode ×1