php脚本返回JS对象而不是数组

时间:2016-06-23 05:25:26

标签: javascript php android arrays android-volley

我想使用php脚本从我的本地服务器获取数据,该脚本应该返回数据而不是对象。

我想使用这个JavaScript数组来使用Android中的volley库来获取数据,以便在listview中显示它们,所以这是php脚本:

 <?php error_reporting(0); include("db_config.php");

 // array for JSON response $response = array();

 // get all items from myorder table $result = mysql_query("SELECT * FROM free_lancer")
                                                         or die(mysql_error());

 if (mysql_num_rows($result) > 0) {

     $response["orders"] = array();

     while ($row = mysql_fetch_array($result)) {
            // temp user array
            $item = array();
             $item["ID_FL"] = $row["ID_FL"];
             $item["FL_LOGIN"] = $row["FL_LOGIN"];

            // push ordered items into response array 
            array_push($response["orders"], $item);
           }
       // success
     // $response["success"] = 1; } else {
     // order is empty 
       $response["success"] = 0;
       $response["message"] = "No Items Found"; } // echoing JSON response echo json_encode($response);

?>

这就是输出:

{

    "orders":[
        {
            "ID_FL":"1",
            "FL_LOGIN":"log"
        },
        {
            "ID_FL":"7",
            "FL_LOGIN":"L"
        }
    ]

}

这是我的活动中的代码:

private static final String url = "http://192.168.1.5/apps.php";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_m);

        listView = (ListView) findViewById(R.id.list);
        adapter = new CustomListAdapter(this, movieList);
        listView.setAdapter(adapter);

        pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();



        // Creating volley request obj
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                Movie movie = new Movie();
                                movie.setTitle(obj.getString("FL_NOM_COMPLET"));
                                movie.setThumbnailUrl(obj.getString("FL_IMAGE"));
                                movie.setRating(((Number) obj.get("RATING"))
                                        .doubleValue());
                                movie.setYear(obj.getInt("FL_NUM_TELE"));

                                // Genre is json array
                               /* JSONArray genreArry = obj.getJSONArray("FL_description_travail");
                                ArrayList<String> genre = new ArrayList<String>();
                                for (int j = 0; j < genreArry.length(); j++) {
                                    genre.add((String) genreArry.get(j));
                                }*/
                                movie.setGenre(obj.getString("FL_description_travail"));

                                // adding movie to movies array
                                movieList.add(movie);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                showMessage("error",error.getMessage());
                hidePDialog();

            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);
    }
...
}

问题是产生一个异常,表示输出无法转换为js数组

1 个答案:

答案 0 :(得分:1)

JSON不是JSONArray,而JSONObject的字段为JSONArray

{  
   "orders":[  
      {  
         "ID_FL":"1",
         "FL_LOGIN":"log"
      },
      {  
         "ID_FL":"7",
         "FL_LOGIN":"L"
      }
   ]
}

您的代码应如下所示:

JsonArrayRequest movieReq = new JsonArrayRequest(url,
//here is the change
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, response.toString());
                hidePDialog();


                // Parsing json
//and here too
                JSONArray jsonArray = response.getJSONArray("orders");
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {
//and here also
                        JSONObject obj = jsonArray.getJSONObject(i);
                        Movie movie = new Movie();
                        movie.setTitle(obj.getString("FL_NOM_COMPLET"));
                        movie.setThumbnailUrl(obj.getString("FL_IMAGE"));
                        movie.setRating(((Number) obj.get("RATING"))
                                .doubleValue());
                        movie.setYear(obj.getInt("FL_NUM_TELE"));

                        // Genre is json array
                       /* JSONArray genreArry = obj.getJSONArray("FL_description_travail");
                        ArrayList<String> genre = new ArrayList<String>();
                        for (int j = 0; j < genreArry.length(); j++) {
                            genre.add((String) genreArry.get(j));
                        }*/
                        movie.setGenre(obj.getString("FL_description_travail"));

                        // adding movie to movies array
                        movieList.add(movie);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                // notifying list adapter about data changes
                // so that it renders the list view with updated data
                adapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.d(TAG, "Error: " + error.getMessage());
        showMessage("error",error.getMessage());
        hidePDialog();

    }
});