2012-01-25 2 views
0

많은 질문을 읽었지만 특정 문제를 발견 할 수없는 것 같습니다 가져 오기 배열을 반환하는 PHP 스크립트가 있으며이를 JSON으로 인코딩합니다. 나는 (내가 그것에 대해 뭔가를 읽을 수는 있지만 단서를 가지고하지 않은 경우)PHP는 JSON 객체를 jQuery 아약스 호출로 반환합니다. 이제 무엇을할까요?

PHP의

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

} 

을 내 PHP 스크립트에는 헤더가없는 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 당신이 정상으로 필드를 액세스 할 수 있도록 한 후, 일반 자바 스크립트 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은 당신이

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

을 좋아하거나 데이터 형식과 시도

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

DEMO

2

에 의해 수동으로 실시 json으로 구문 분석 할 수 있습니다에 대한 분석 과정을 거치게됩니다 그래서 jsondataType을 설정 JSON 또는 $ .ajax 대신 $ .getJSON을 사용하십시오.

관련 문제