好的,对于 Web 应用程序,对 python 的支持将取决于浏览器是否具有作为插件提供或内置于浏览器中的 python 支持。对于大多数查看应用程序的人来说,依靠这种情况可能不是一个好主意。如果这样做,只需将脚本包含<SCRIPT type="text/x-python" src="path-to-your-pyfile.py">
在 html 的标记中即可。作为替代方案,由于 html5,javascript 现在支持写入包含文本和二进制数据的文件。请参阅此处的文件 api 。
如果使用文件 api 出现问题,您始终可以创建一个指向文件的链接,供用户使用数据 URI 从 javascript 中保存,如下所示:
数据:文本/纯文本;base64,aGVsbG8gZnJvbSBhIGRhdGEgdXJpISEh
这是一个 html 文件的示例,它从 javascript 注意我推出了自己的 base64 编码器,但有许多 js 库可用于此。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<SCRIPT type="text/javascript" >
var BASE_64_ALPHABET =//for encoding base64
[
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'0','1','2','3','4','5','6','7','8','9','+','/'
];
var BASE_64_PAD = '=';
function valueAt(source,index)
{
var result = null;
if(source.charAt)
result = source.charAt(index);
else
result = source[index];
if(result.charCodeAt)
result = result.charCodeAt(0);
if(result === null | result === undefined)
return 0;
return result;
}
function toBase64(data, offset, length)
{
var padSize = (3-(length % 3));
if(padSize == 3 && length != 0)
padSize = 0;
var bufferSize = ((4*(length-(length%3)))/3); + padSize;
var buffer = new Array(bufferSize);
var iterationLimit = length + (length % 3) - 1;
var octetMask = 0xFF;
var sextetMask = 0x3F;
for(var sourceIndex=0,destinationIndex=0;sourceIndex<iterationLimit;sourceIndex+=3,destinationIndex+=4)
{
var readBlock =
(
((valueAt(data, offset+sourceIndex) & octetMask) << 16) |
((valueAt(data, offset+sourceIndex+1) & octetMask) << 8) |
(valueAt(data, offset+sourceIndex+2) & octetMask)
);
buffer[destinationIndex] = BASE_64_ALPHABET[(readBlock >>> 18) & sextetMask];
buffer[destinationIndex+1] = BASE_64_ALPHABET[(readBlock >>> 12) & sextetMask];
buffer[destinationIndex+2] = BASE_64_ALPHABET[(readBlock >>> 6) & sextetMask];
buffer[destinationIndex+3] = BASE_64_ALPHABET[readBlock & sextetMask];
}
for(var i = 0; i < padSize; i++)
buffer[buffer.length - 1 - i] = BASE_64_PAD;
return buffer.join("");
}
function makeDataURI()
{
var data = document.getElementById("datasource").value;
var mime = document.getElementById("mimesource").value;
alert("data:"+mime+";base64,"+toBase64(data,0,data.length));
}
</SCRIPT>
</head>
<body>
<INPUT id="datasource" type="text" value="enter your file data here"></INPUT>
<INPUT id="mimesource" type="text" value="enter your mime type here"></INPUT>
<INPUT type="button" onclick="makeDataURI();" value="Generate URI"></INPUT>
</body>
</html>