簡體   English   中英

來自PHP腳本的JSON響應

[英]JSON response from PHP script

我正在為Android構建注冊系統。 我可以將數據添加到數據庫中,這很好。 現在,我想添加一些JSON來通知用戶成功注冊或其他錯誤。

{
  "status":"success",
  "message":"Successful Registration"

}

要么

 {
  "status":"fail",
  "message":"Please enter your name"

}

等等

這是我的PHP腳本。

<?php
   require "init.php";
   $j = new stdClass();
   $name = $_POST['name'];
   $user_name = $_POST['user_name'];
    $user_pass = md5(md5($_POST['user_name']).$_POST['user_pass']);
    if(!$name){
    json_encode(array('status' => 'fail', 'message' => 'Please enter your    
    name'));
   }
   $sql_query = "insert into user_info    
  values('$name','$user_name','$user_pass');";

   if(mysqli_query($con,$sql_query)){

    json_encode(array('status' => 'success', 'message' => 'Successfully 
    registered'));

  }else{

   json_encode(array('status' => 'fail', 'message' => 'Could not   
   register'));
  }



 ?>

使用此腳本,即使我成功添加了數據,我也無法從Java代碼中檢測到任何JSON響應。

  private void registerUser(final String name, final String userName,
                          final String password) {
    // Tag used to cancel the request
    String tag_string_req = "req_register";


    StringRequest strReq = new StringRequest(Request.Method.POST,
            "MY_LINK_GOES_HERE", new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d("Response", "Register Response: " + response.toString());

            Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();

            // Launch login activity
            Intent intent = new Intent(
                    Register.this,
                    MainActivity.class);
            startActivity(intent);
            finish();
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Error", "Registration Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();

        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("name", name);
            params.put("user_name", userName);
            params.put("user_pass", password);

            return params;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

Log.d("Response", "Register Response: " + response.toString());

什么也沒給我

有任何想法嗎?

謝謝。

首先,您應該在問題中提到您正在使用android-volley庫,或者至少使用tag 其次,如果您嘗試解析JSON響應,則應使用JsonObjectRequest實例來執行此操作。 假設您的php腳本正在發送正確的JSON ,則可以使用volley嘗試簡單而直接的方法,如下所示:

JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    response = response.getJSONObject("args");
                    String site = response.getString("site"), network = response.getString("network");
                    View view = findViewById(R.id.activity_layout);
                    Snackbar.make(view, "Site : " + site + " Network : " + network, Snackbar.LENGTH_INDEFINITE).show();
                } catch (JSONException e) {
                    Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getBaseContext(), "Error Listener", Toast.LENGTH_LONG).show();
            }
        });

        Volley.newRequestQueue(this).add(jsonRequest);

假設您的JSON是這樣的:

{
  "args": {
    "network": "somenetwork", 
    "site": "code"
  }, 
  "args2": {
    ...
  }, 
  "args3": "...", 
  "args4": "..."
}

現在,根據要發送的JSON ,您可以嘗試任意組合。 您也可以研究這個非常有用的教程 希望這可以幫助。 讓我知道您是否需要更多幫助。

嘗試注冊時,我的應用程序遇到了同樣的問題。 我想檢查用戶是否注冊以及用戶名是否可用。

所以我所做的是:

PHP文件:

<?php
try {
    $handler = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
    echo $e->getMessage();
    die();
}

$username = $_POST['username'];
$password=$_POST['password'];
$email = $_POST['email'];
$dateCreated = $_POST['dateCreated'];
$android_version= $_POST['android_version'];
$api_level = $_POST['api_level'];
$check = $handler->query("SELECT * FROM table WHERE username = '$username'");
$don = array();
     if($check->rowCount() > 0){
          $don = array('result' =>TRUE);
          die();
     }else{
          $don = array('result' =>FALSE);
          $handler->query("INSERT INTO table(id, username, password, email, dateCreated, activated, Android_Version, API_Level) VALUES('', '$username','$password','$email', '$dateCreated', 0, '$android_version', '$api_level')");
     }

echo json_encode($don);
?>

Android:

私有類MyInsertDataTask擴展了AsyncTask {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(YourActivity.this);
        pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.setIndeterminate(true);
        pDialog.setMessage(getString(R.string.dialog_rate_data_submit));
        pDialog.setCancelable(false);
        pDialog.setInverseBackgroundForced(true);
        pDialog.show();
    }

    @Override
    protected Boolean doInBackground(String... params) {
        nameValuePairs = new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("username", uName));
        nameValuePairs.add(new BasicNameValuePair("password", pass));
        nameValuePairs.add(new BasicNameValuePair("email", email));
        nameValuePairs.add(new BasicNameValuePair("dateCreated", date));
        nameValuePairs.add(new BasicNameValuePair("android_version", release));
        nameValuePairs.add(new BasicNameValuePair("api_level", String.valueOf(sdkVersion)));

        try
        {
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(AppConstant.REGISTER_URL);
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            response = httpClient.execute(httpPost);
            httpEntity = response.getEntity();
            is = httpEntity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                result.append(line);
            }
            Log.e("Responce", result.toString());
            if (result != null) {
                data = new JSONObject(result.toString());
                usernameExists = data.getBoolean("result");
            }
        }
        catch(Exception e)
        {
            Log.e("Fail 1", e.toString());
        }
        return  usernameExists;
    }
    @Override
    protected void onPostExecute(Boolean aVoid) {
        super.onPostExecute(aVoid);
        pDialog.dismiss();
        if (aVoid){
            Snackbar.with(YourActivity.this).type(SnackbarType.MULTI_LINE).text(getString(R.string.username_exists_message)).color(Color.parseColor(AppConstant.ENABLED_BUTTON_COLOR)).show(getActivity());
        }else {
            Toast.makeText(YourActivity.this, getString(R.string.created_successfully), Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(YourActivity.this, MainActivity.class);
            startActivity(intent);
            YourActivity.this.finish();
        }

    }
}

結果是,如果用戶名存在,則會彈出一條消息,提示用戶名已存在,否則用戶將進行注冊

結果:

在此處輸入圖片說明

我修好了它! 這是一個PHP問題。 這是我的解決方案。

<?php
  require "init.php";
  header('Content-type: application/json');
  $name = $_POST['name'];
  $user_name = $_POST['user_name'];
  $user_pass = md5(md5($_POST['user_name']).$_POST['user_pass']);

        $sql_query = "select * from user_info WHERE user_name  
  ='".mysqli_real_escape_string($con, $user_name)."'";

        $result = mysqli_query($con, $sql_query);   

        $results = mysqli_num_rows($result);

        if ($results){
            $don = array('result' =>"fail","message"=>"Username exists. User               
        a different one");
        }else{

            $sql_query = "insert into user_info  
       values('$name','$user_name','$user_pass');";

            if(mysqli_query($con,$sql_query)){

            $don = array('result' =>"success","message"=>"Successfully  
            registered!Well done");

            }
        }

    echo json_encode($don);

  ?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM