javascript 使用 GET 请求发送数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31930927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send array with GET Request
提问by spenf10
I am making a get request form Javascript to Python. And I am trying to pass a 2D array so something like
我正在向 Python 发出 Javascript 的 get 请求表。我正在尝试传递一个二维数组,例如
[["one", "two"],["foo", "bar"]]
And here is what I am currently trying but it is not working.
这是我目前正在尝试但不起作用的方法。
So in my javascript I have an array that look similar to the one above, and then pass it like this
所以在我的 javascript 中,我有一个类似于上面的数组,然后像这样传递它
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "http://192.67.64.41/cgi-bin/hi.py?array=" + myArray, false );
xmlHttp.send( null );
And then in python I get it like this
然后在python中我得到了这样的
import cgi
form = cgi.FieldStorage()
array = form.getvalue("array")
But it doesn't come out right, in python then if I were to do
但结果不正确,在 python 中,如果我要这样做
print array[0]
#I get -> "o"
print array[1]
#I get -> "n"
print array[2]
#I get -> "e"
and so on, but if I what I want is
等等,但如果我想要的是
print array[0]
#output -> ["one", "two"]
How can I accomplish this?
我怎样才能做到这一点?
Thanks
谢谢
回答by Carl Markham
You can't simply pass an array as a query parameter. You will need to iterate over the array and add it so the URL string such as ?array[]=one&array[]=two
您不能简单地将数组作为查询参数传递。您将需要遍历数组并将其添加到 URL 字符串中,例如?array[]=one&array[]=two
Here is a basic jsfiddleas an example
这里以一个基本的jsfiddle为例
var a=['one', 'two'];
var url = 'www.google.com';
for (var i=0; i<a.length; ++i) {
if (url.indexOf('?') === -1) {
url = url + '?array[]=' + a[i];
}else {
url = url + '&array[]=' + a[i];
}
}
console.log(url);
回答by Dalen
No, you don't have to. And, yes, you can do just that! You can pass it as one string like you did, and then get it and evaluate it in Python.
不,你不必。而且,是的,您可以做到这一点!您可以像以前一样将它作为一个字符串传递,然后获取它并在 Python 中对其进行评估。
You can use:
您可以使用:
evaldict = {}
array = eval("[[1, 2, 3], [4, 5, 6]]", evaldict)
Although I forced the scope of evaluation to be encapsulated in a dict, THIS IS NOT SECURE!
尽管我强制将求值范围封装在 dict 中,但这并不安全!
Because someone can pass some other Python expression to be evaluated. Therefore better use literal_eval() from ast module which doesn't evaluate expressions.
因为有人可以传递一些其他的 Python 表达式来进行评估。因此,最好使用不计算表达式的 ast 模块中的literal_eval()。
I suggest you tu use jquery and its post() method to do this, use a POST HTTP method instead of GET.
我建议您使用 jquery 及其 post() 方法来执行此操作,使用 POST HTTP 方法而不是 GET。
Also, this could be nice and securely done using json (send the json instead of just stringifying JS array manually. And using it to avoid evaluating a list directly (in Python).
此外,这可以使用 json 很好且安全地完成(发送 json 而不是手动将 JS 数组字符串化。并使用它来避免直接评估列表(在 Python 中)。
Here is the client side using jquery:
这是使用 jquery 的客户端:
<html><head><title>TEST</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
pyurl = "http://example.com/cgi-bin/so.py";
function callpy (argdict) {
$.post(pyurl, argdict, function (data) {
// Here comes whatever you'll do with the Python's output.
// For example:
document.getElementById("blah").innerHTML = data;
}, "text");
};
var myArray = [["one", "two"], ["foo", "bar"]];
// This is array shape dependent:
function stringify (a) {
return "['" + a.join("', '") + "']";
};
myArrayStr = "[";
for (x = 0; x<myArray.length; x++) {
myArrayStr += stringify(myArray[x]) +", ";
}
myArrayStr += "]";
// This would be better, but it is library dependent:
//myArrayStr = JSON.stringify(myArray);
</script>
</head><body>
<a href="#" onclick="javascript:callpy({'array': myArrayStr});">Click me!</a>
<p id="blah">
Something will appear here!
</p>
</body></html>
And this is the server-side CGI:
这是服务器端的 CGI:
#! /usr/bin/env python
try:
# This version of eval() ensures only datatypes are evaluated
# and no expressions. Safe version of eval() although slower. It is available in Python 2.6 and later
from ast import literal_eval as eval
except ImportError:
import sys
print "Content-Type: text/html\n"
print "<h1>literal_eval() not available!</h1>"
sys.exit()
import cgi, cgitb
import sys
cgitb.enable()
print "Content-Type: text/html\n"
i = cgi.FieldStorage()
q = i["array"].value.strip()
print "I received:<br>"
print q
# Put here something to eliminate eventual malicious code from q
# Check whether we received a list:
if not q.startswith("[") and not q.endswith("]"):
print "Wrong query!"
sys.exit()
try: myArray = eval(q)
except: print "Wrong query!"; sys.exit()
if not isinstance(myArray, list):
print "Wrong query!"
sys.exit()
print "<br>Evaluated as:<br>"
print myArray
Now, note that using json on both sides would be faster and more flexible.
现在,请注意,在双方使用 json 会更快、更灵活。