2014-05-09 2 views
0

나는 나 자신과 친구를 위해 기본 채팅 시스템을 만들려고 노력하고있다. 매우 간단하지만, 아약스가 나를 상당히 혼란스럽게합니다. 저는 아약스를 사용하여 사용자 이름을 설정 한 PHP 페이지를 요청하고 마지막으로 채팅을 다운로드했습니다. 그러나, 나는 PHP 페이지 에코를 읽는 방법을 모른다. 온라인으로 확인했지만 많은 변형이 있기 때문에 혼란 스럽습니다. 누구든지 제발 좀 도와 줄래?jQuery AJAX를 통해 PHP 변수를 설정하고 가져 오기

Scripts.js (jQuery를 이미 연결로)

// on document ready + called every second 

$.ajax({ 
      url: 'download.php', 
      type: 'REQUEST', 
      datatype: 'json', 
      data: ({ 
       last_downloaded: latestTimestamp, 
       username: username 
      }), 
      success: function (data) { 
       console.log(data.message[0].time); 
       // Uncaught TypeError: Cannot read property '0' of undefined 
       // how do I get the time from the json? 
       // {"message":{"chat":"Hello, world!","time":"2014-05-09 17:32:00,"username":"Josue"},"message":{"chat":"This is my second message.","time":"2014-05-09 17:32:05,"username":"Josue"}} 

      } 
     }); 

      latestTimestamp = data.message[0].time; 
      downloadingTimer = setTimeout(actuate, timeoutValues[currentTimeoutIndex]); 

    } 

download.php

이 무엇인지 일반 문자열로 내 PHP 페이지 에코 (지금의 형식이 JSON) :

[ 
    { 
     "chat":"Hello, world!", 
     "time":"2014-05-09 17:32:00", 
     "username":"Josue" 
    }, 
    { 
     "chat":"This is my second message.", 
     "time":"2014-05-09 17:32:05", 
     "username":"Josue" 
    } 
] 

내 페이지 상단에 header("Content-Type: application/json");이 있습니다. 내가 뭔가 잘못하고 있는거야?

+0

인쇄 오류는 어디에서 발생 했습니까? 이후 ajax 호출 이후'latestTimestamp = data.message [0] .time;'하지만 데이터 변수는 더 이상 그 범위에 있지 않습니다! – ReGdYN

답변

1

JSON 응답 형식이 잘못되었습니다. 날짜 기록 다음의 쉼표는 대신 외부의, 따옴표 안에 : 또한

 "time":"2014-05-09 17:32:00,"  username":"Josue" 
    }, 

, 당신은 메시지의 배열을 표현하기 위해 대괄호를 사용한다. 귀하의 JSON은 다음과 같아야합니다

{ "message": [ 
    { 
     "chat":"Hello, world!", 
     "time":"2014-05-09 17:32:00", 
     "username":"Josue" 
    }, 
    { 
     "chat":"This is my second message.", 
     "time":"2014-05-09 17:32:05", 
     "username":"Josue" 
    } 
] 
} 

당신은 JSON 문자열로 PHP 배열을 변환하거나 객체에 json_encode() 기능을 사용할 수 있습니다 : 메시지가 배열이 아닌 때문에

<?php 
    $my_arr = array("message" => array()); 
    $my_arr["message"][] = array("chat" => "Hello, World!", "time" => "2014-05-09 17:32:05", "username" => "Josue"); 

    echo json_encode($my_arr); 
?> 
+0

감사합니다. 도움이되었습니다. –

0

내가 그 실패를 생각한다. 메시지는 개체이므로 더 많은 메시지가있는 경우 보내는 방법을 다시 디자인하십시오. 귀하의 PHP 스크립트는 json 배열에 메시지를 넣어야하므로 0 인덱스로 첫 번째를 얻을 수 있습니다

0

두 가지 문제가 있습니다.

하나가 JSON 형식이 올바르지 않습니다. "time":"2014-05-09 17:32:00," username":"Josue""time":"2014-05-09 17:32:00", "username":"Josue"이어야합니다. 브라우저의 오류 콘솔에서이를 보았을 것입니다.

둘째, 메시지를 배열에 넣어야합니다. 그렇지 않으면 각 새 메시지에 message 속성을 덮어 쓰는 것만으로 프런트 엔드가 PHP 파일의 가장 낮은 메시지로 끝나게됩니다. 이 에코한다

PHP : 당신 JS에서

{ 
    messages: [ 
     { 
      "chat":"Hello, world!", 
      "time":"2014-05-09 17:32:00", 
      "username":"Josue" 
     }, 
     { 
      "chat":"Second message", 
      "time":"2014-05-09 17:32:00", 
      "username":"Josue" 
     } 
    ] 
} 

그리고,이 어레이는 각각의 메시지와 data.messages[0]data.messages[1], 주도로, data.messages 것이다.

+0

'data.messages'의'messages' 부분은 무엇입니까? 그게 어디로 갈거야? –

+0

죄송합니다. JSON 출력을 수정하여 수정했습니다. – jraede

0

JSON을 다시 포맷 한 후에도 JSON 문자열을 자바 스크립트 객체로 구문 분석하려고 할 수 있습니다.

var parsed_data = $.parseJSON(data); 
// extract data here parsed_data[key] 
관련 문제