4

サーバーから返された JSON 文字列を解析しようとすると、jquery (バグ/エラー) が発生します。

Timestamp: 10/04/2013 21:05:12
Error: SyntaxError: JSON.parse: unexpected character
Source File: http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
Line: 3

そして、ヘッダー Content-type が 'application/json' に設定されていない場合は JSON.parse が正常に機能しますが、Content-type が json に設定されている場合は機能しないことに気付きました。なぜこれが起こるのでしょうか?

動作しないコード:

コントローラーコード:

  $response = array('data' => array('msg' => 'Form did not validate'), 'response_handler_fn' => 'sign_up_response_handler_fn');
  $this->getResponse()->setHttpHeader('Content-type','application/json');
  return $this->renderText(json_encode($response));

Javascript:

// ...
success: function( response ) {
var responseData = $.parseJSON(response);
}

ヘッダー

Cache-Control   no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection  Keep-Alive
Content-Length  92
Content-Type    application/json
Date    Wed, 10 Apr 2013 20:05:12 GMT
Expires Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive  timeout=15, max=100
Pragma  no-cache
Server  Apache
X-Powered-By    PHP/5.3.5

応答:

{"data":{"msg":"Form did not validate"},"response_handler_fn":"sign_up_response_handler_fn"}

機能するコード

コントローラ:

  $response = array('data' => array('msg' => 'Form did not validate'), 'response_handler_fn' => 'sign_up_response_handler_fn');
  return $this->renderText(json_encode($response));

動作するものと同じJavascript

ヘッダー:

Cache-Control   no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection  Keep-Alive
Content-Length  92
Content-Type    text/html; charset=utf-8
Date    Wed, 10 Apr 2013 20:09:04 GMT
Expires Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive  timeout=15, max=100
Pragma  no-cache
Server  Apache
X-Powered-By    PHP/5.3.5

応答:

{"data":{"msg":"Form did not validate"},"response_handler_fn":"sign_up_response_handler_fn"}
4

3 に答える 3

10

dataType呼び出しのオプションを指定しない場合、jQueryは、応答で返されたヘッダー$.ajaxに従って応答を解析しようとします。Content-Type

したがって、 に何も指定せず、ヘッダーにdataType特別な指定をしないと、テキストとして解析されます。Content-Typeresponse

に何も指定せず、ヘッダーにdataType「json」を指定すると、JSON (Javascript オブジェクト リテラル) として解析されます。Content-Typeresponse

を "json" として指定すると、ヘッダーdataTypeが何であれ、JSON (Javascript オブジェクト リテラル) として解析されます。Content-Typeresponse

JSON.parse文字列のみを受け入れるため、オブジェクト リテラルを に渡そうとすると失敗します。

したがって、何を設定し、何を呼び出そうとしているか ( JSON.parse) を判断し、適切な組み合わせを使用する必要があります。

于 2013-04-11T04:30:05.060 に答える
0

Content-type が json に設定され、応答を json として渡す場合は、

dataType:"json"

それ以外の場合は機能しません。問題があると思います。あなたのajaxも表示されない場合。

于 2013-04-11T04:24:01.643 に答える