2011-11-10 5 views
1

何か変なことが起きています。私のAJAXリクエストは配列を返していますが、全体が文字列です。AJAXリクエストが長い文字列を返す

これは基本的にそれを合計:

PHP

$item = array(); 

$item[] = array(
    'title'  => 'awesome title', 
    'permalink' => 'some url' 
); 

json_encode($item); 

jQueryの

$.ajax({ 
    type: 'post', 
    url: ajaxurl, 
    data: { 
     action: 'a_grid_callback', 
     type: method 
    }, 
    success: function(msg) { 
     console.debug(msg); 
    } 
}); 

デバッグ戻り、この:

[{"title":"awesome title","permalink":"some url"}]0 

もし私がalert(msg.length)をやったなら、私は上記のコードの長さに相当する長い数字を得るでしょう。

+0

しようような何かをする必要があります'dataType:json'を設定します.brのように見えますowserはレスポンスを文字列として解釈しています。 –

+0

私はそれを試してみましたが、私は全く反応がありませんでした:/ – daryl

+0

何らかの奇妙な理由のために、今働いています。これは、48時間近く滞在を続けていることによるものです。それを答えとして書くと、あなたは目を覚ます。 – daryl

答えて

1

ブラウザが文字列として応答を解釈しているようdataType: 'json'が見える設定にしてください。配列

として

1
$item = array(
    'title'  => 'awesome title', 
    'permalink' => 'some url' 
); 

json_encode($item); 


// Add exit here 
exit; 
+0

効果がなかったので、質問を編集して画像を表示しました。 – daryl

+0

ありがとう、私はこれがdataType: 'JSON'が以前に動作していなかった理由とは何かを持っている可能性があると信じています。 – daryl

1
$.ajax({ 
    type: 'post', 
    url: ajaxurl, 
    data: { 
     action: 'a_grid_callback', 
     type: method 
    }, 
    success: function(msg) { 
     eval("data="+msg); 
     var title = data.title; 
     console.debug(title); 
    } 
}); 
0

非連想配列の出力は、この

json_encode($item, JSON_FORCE_OBJECT) 

またはこの

$item[foo] = array(
    'title'  => 'awesome title', 
    'permalink' => 'some url' 
); 

またはこの

$item = array(
    'title'  => 'awesome title', 
    'permalink' => 'some url' 
);