LoginSignup
2
3

More than 5 years have passed since last update.

FuelPHPのRestでJSONを返した時にはまるなど

Last updated at Posted at 2016-03-01

JSON形式で返ってきてるはずなのに。

うけとったJavaScript側でふたたびJSON.parseするハメに。
処理がダサい。原因もダサい。ただのパラメータ不足だった。

修正前

JavaScript (jQuery)
function update_hoge() {
    var params = {foo: "bar"};
    $.ajax({
        type: "POST",
        url: "/index/update_hoge",
        data: params,
    }).then(function(data){
        console.log(JSON.parse(data).text); // <- この一行がダサい
    });
}
PHP (FuelPHP)
class Controller_Index extends Controller_Rest {

    public function update_hoge() {
        $this->format = 'json';
        $json = ['text' => 'いろいろ'];
        return $this->response($json);
    }

}

修正後

$.ajax()のオプションに dataType:"json" を書き忘れてた。

JavaScript (jQuery)
function update_hoge() {
    var params = {foo: "bar"};
    $.ajax({
        type: "POST",
        url: "/index/update_hoge",
        data: params,
        dataType: "json",
    }).then(function(data){
        console.log(data.text); // <- すぐとれる
    });
}

FuelPHPのRestについて

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3