2012-01-25 3 views
0

私はたくさんの質問を読んできましたが、私の特定の問題を見つけることができないようです。 フェッチ配列を返すPHPスクリプトがあり、それをJSONにエンコードします。私は私のPHPスクリプトには、ヘッダー(私はそれについて何かを読みますが手掛かりを持っていない)PHPはJSONオブジェクトをjQueryのajax呼び出しに戻します。今は何ですか?

PHP

if (mysql_num_rows($pquery) == 1) { 
    $result = mysql_fetch_assoc($pquery); 
    echo json_encode($result); 

} 

jQueryの

$('#c_search').submit(function(){ 
     data = ($(this).serialize()); 

    $.ajax({ 
     url: 'actions/get_company.php', 
     type: 'POST', 
     data: data, 
     cache: false, 
     success: function(text){ 
      alert (text); 
      alert(text[1]); // not right! 
      alert(text.company[0]);// not right! 
     } 

}).error(function(){ 
    alert('error'); 
}) 
return false; 

}) 

私は戻って取得テキストを持っていません。私は、独自の変数に、個々の作品を置くことができますので、私はこれを適切に処理するにはどうすればよい

{"id":"167","company":"ZEN","street":"1 S Congress Ave","email":"[email protected]","state":"TX","zip":"78704","phone":"512-555-1212"} 

+0

それは固定されました!皆さんありがとうございます...スタックが許す場合、6分でチェックします。 –

答えて

2
data: data, 
cache: false, 
dataType: 'json', // <!-- indicate that the response type is JSON => not necessary if your PHP script correctly sets the Content-Type: application/json response header 
success: function(text) { 
    alert(text.id); 
    alert(text.company); 
    alert(text.street); 
    alert(text.email); 
    ...  
} 
+0

これらの答えのすべてが正しい方向に私を指摘しました。私がラインを下ったとき、これは単純な意味で作られたものであり、最初に働いたものです。投票していただきありがとうございます。 –

3

あなたはjQueryのJSONとしてレスポンスを解析持つようにdataTypeを使用することができます:あなたは、通常のようにフィールドにアクセスできるように

$.ajax({ 
    url: 'actions/get_company.php', 
    dataType: 'json', 

    [..] 

dataはその後、通常のJavascript Object次のようになります。

alert (data.street); 
2

ご利用いただけますJSON.parse()

$('#c_search').submit(function(){ 
     data = ($(this).serialize()); 

    $.ajax({ 
     url: 'actions/get_company.php', 
     type: 'POST', 
     data: data, 
     cache: false, 
     success: function(text){ 
      var obj = JSON.parse(text); 
      alert (text); 
      alert(text[1]); // not right! 
      alert(text.company[0]);// not right! 
     } 

}).error(function(){ 
    alert('error'); 
}) 
return false; 

}) 
1

JSONはあなたのために解析されるようにjsondataTypeを設定

$.ajax({ 
dataType:'json', 
}); 

を好きか、君は

$.ajax({ 
dataType:'json', 
success:function(json){ 
    var parsedJSON = $.parseJSON(json); 
}, 
}); 

DEMO

2

でのJSONてmanualyを解析できるデータ型を試してみてください:JSONをか$ .ajaxの代わりに$ .getJSONを使用してください。

関連する問題