我试图将ArrayList发送到PHP($_POST(并将其用作数组。我使用 Android Asynchronous Http 客户端 http://loopj.com/android-async-http/
我的代码
ArrayList<String> array = new ArrayList<String>();
array.add("1");
array.add("2");
array.add("3");
RequestParams params = new RequestParams();
params.put("descr_array", array );
AsyncHttpClient client = new AsyncHttpClient();
client.post(StaticValues.SERVER_PAGE, params, new AsyncHttpResponseHandler() { ... }
在 PHP 中
$descrarray[] = $_POST['descr_array'];
仅以字符串形式显示一个项目。
$result = print_r($_POST);
print(json_encode($result));
调试代码显示
数组 ( [descr_array] => 1 (
只有一个字符串,我该如何解决?
如果要获取所有值,请写入:
RequestParams params = new RequestParams();
params.put("descr_array_1", array.get(0) );
params.put("descr_array_2", array.get(1) );
params.put("descr_array_2", array.get(2) );
但我更喜欢您使用 Gson 将数组转换为字符串并仅使用一对:
Gson gson = new Gson();
String out = gson.toJson(array);
params.put("descr_array", out );
这是对我有用的:
RequestParams params = new RequestParams();
for (String val : array) {
params.add("descr_array[]", val);
}
它不需要您添加额外的标题或导入其他库,并且适用于JSON
和XML
。
这里要注意的重要一点是使用 add
而不是 put
.看看两者之间的区别。
这对
我有用...
Map<String, String> aMap = new HashMap<String, String>();
aMap.put("f_name" ,"");
aMap.put("l_name" ,"");
aMap.put("email" ,edtEmail.getText().toString());
RequestParams params = new RequestParams();
params.put("user",aMap);
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, n.....