Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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について

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした