簡體   English   中英

Ajax + JSON Decode + Slim PHP問題?

[英]Ajax + JSON Decode + Slim PHP problems?

好吧,我似乎無法從我的ajax調用解碼JSON,它將用戶數據發布到我的api,它是用超薄的php構建的。

這是我的ajax ..

var jsonData;
jsonData = [
      {
        username: "user",
        password: "pass"
      }
    ];

$.ajax({
  type: "POST",
  url: "http://localhost/api/user/auth",
  data: {
    user: JSON.stringify(jsonData)
  },
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data) {
    alert("You are good!");
  },
  error: function(xhr, type) {
    alert("Y U NO WORK?");
  }
});

這是我的SLIM PHP代碼..

$app->post('/user/auth', function () use ($app) {
    try {
         $requestBody = $app->request()->getBody(); //This works

         //RequestBody is: user=%5B%7B%22username%22%3A%22user%22%2C%22password%22%3A%22pass%22%7D%5D         

         $json_a = json_decode($requestBody); //This doesn't work

         print_r($json_a); //Has no output?

         $username = $json_a['user']['username']; //Therefore this doesn't work?

    } catch(Exception $e) {
         echo '{"error":{"text": "'. $e->getMessage() .'"}}';
    }
});

正如您在注釋中所看到的那樣,requestBody等於:

user=%5B%7B%22username%22%3A%22user%22%2C%22password%22%3A%22pass%22%7D%5D  

但是,我似乎無法解碼它,因為print_r($ json_a)沒有效果。

非常感謝任何幫助,謝謝。

嘗試

$params_str = urldecode($requestBody);
parse_str($params_str, $params_arr);
$user = json_decode($params_arr['user']);

你做錯了...你是通過郵件發送數據所以你shoudl從那里抓住json字符串而不是試圖手動讀取請求正文...類似的東西

$req = $app->request();
$json = json_decode($req->post('user'));

現在,如果你真的想發送一個完全不同的json請求體,但它需要更改你的js。 您需要將processData設置為false,以便它不會嘗試在內部對data值進行編碼。 這也意味着你必須對它進行預編碼:

$.ajax({
  type: "POST",
  url: "http://localhost/api/user/auth",
  data: JSON.stringify({user: jsonData}), // gotta strinigfy the entire hash
  processData: false,
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data) {
    alert("You are good!");
  },
  error: function(xhr, type) {
    alert("Y U NO WORK?");
  }
});

問題是“用戶”密鑰。 它沒有正確格式化為json解碼。 我完全刪除了它,因為它無論如何都沒有必要。

所以我改變了:

data: {
    user: JSON.stringify(jsonData)
  },

 data: JSON.stringify(jsonData)

而且,我還實現了@ air4x系列:

$json_a = json_decode(urldecode($requestBody));

暫無
暫無

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

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