javascriptファイルからaphaxリクエストをcakephpコントローラに送信しようとしています。 ajaxは単純なjsonオブジェクトを送信しています(この例では単純化のためにハードコードしています)。CakePHP 3:Ajaxレスポンスが200応答コードと解析エラーを返しています
私がログをとると、サーバーはjson文字列をオブジェクトにデコードできます。 $this->Votes->delete
関数が正常に呼び出されます。私の問題は、私がまだエラーメッセージを受け取っていることを除いて、すべてがうまくいくということです。
以下は私のコードであり、以下はそれから得られる出力です。
Javascriptを:
function unvote() {
$.ajax({
type: 'POST',
url: '../votes/unvote',
async: false,
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({'post_id':1}),
success: function(data, textStatus, jqXHR){
console.log(data);
console.log(textStatus);
console.log(jqXHR);
}.
error: function(jqXHR, textStatus, errorThrown){
// this block gets triggered with a 200 response
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
},
});
}
PHP:投票コントローラー
public function unvote(){
$this->autoRender = false;
$vote = $this->Votes->newEntity();
if ($this->request->is('ajax')) {
$data = $this->request->input('json_decode');
$vote = // get the correct vote from the database and save into this object
if ($this->Votes->delete($vote)) {
$this->response->body('Success');
$this->response->statusCode(200);
} else {
$this->response->body('Failure');
$this->response->statusCode(500);
}
}
$this->response->type('json');
return $this->response;
}
AJAXの応答:
Object{ readyState=4, responseText="", status=200, statusText="Ok", more...}
parsererror
SyntaxError:JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
> return window.JSON.parse(data + "");
正しいヘッダー( "Content-Type:application/json"、true)を送信しましたか、なぜ 'window.JSON.parse'をやっていますか?あなたは 'dataType: 'json'jsonデータを介して期待しているので、jQueryとして解析されるので、自分で解析する必要はありません。 – JustOnUnderMillions
あなたの応答が無効です。ブラウザ(開発者コンソール - >ネットワークタブ)のF12からリクエストログを確認してください。 – JustOnUnderMillions
'status = 200'は、http呼び出しと関係しています。ステータス200の意味は次のとおりです。何かが正しく送信されました。これ以上何もない。それは、送信されたコンテンツについては何も言いません。 – JustOnUnderMillions