【发布时间】:2015-12-15 07:16:49
【问题描述】:
我有将参数发送到 php 并以 JSON 格式获取结果的代码:
private void details_location(int id){
HashMap<String, String> parameter = new HashMap<>();
parameter.put("id", id);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url, new JSONObject(parameter), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONArray respon=(JSONArray)response.get("location");
for (int i = 0; i < respon.length(); i++) {
JSONObject person = (JSONObject) respon.get(i);
id_location= person.getString("id_location");
address= person.getString("address");
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
我有用于处理查询 Mysql 的文件 php 并以 JSON 格式输出:
<?php
require_once('db_connect.php');
if(isset($_GET['id'])){
$id=$_GET['id'];
$action="SELECT * FROM locaions WHERE id_location=\"$id\";";
$query=mysqli_query($db_connect, $action);
if (mysqli_num_rows($query) > 0)
{
$json['location']=array();
while($row=mysqli_fetch_assoc($query)){
$data=array();
$data["id_location"]=$row["id_location"];
$data["address"]=$row["address"];
array_push($json['location'], $data);
}
}
mysqli_close($db_connect);
echo json_encode($json);
}
else{
$action="SELECT * FROM locaions WHERE id_location=4;";
$query=mysqli_query($db_connect, $action);
if (mysqli_num_rows($query) > 0)
{
$json['location']=array();
while($row=mysqli_fetch_assoc($query)){
$data=array();
$data["id_location"]=$row["id_location"];
$data["address"]=$row["address"];
array_push($json['location'], $data);
}
}
mysqli_close($db_connect);
echo json_encode($json);
}
?>
当我运行程序时,结果总是显示带有id_location=4 的位置(其他语句)。为什么isset($_GET['id']) = false ?如何向 PHP 发送参数并以 JSON 格式获取结果?
【问题讨论】:
-
要回答“为什么 isset($_GET['id']) 为假”的问题,您应该打印您收到的值以及您尝试访问的 URL,这样您就会明白更好的事情发生了。
标签: php android android-studio android-volley