2016-09-16 4 views
2

안녕하세요, msg를 undefined로 반환하는이 스크립트가 있습니다. consol에서는 jsondata를 반환하지만 경고를하거나 확인하려고 할 때 작동하지 않습니다.ajax success : function (msg) undefined

$(function() { 
    $(".aplica_bt").click(function(e) { 
     e.preventDefault(); 
     var href = $(this).attr('href'); 

     $.ajax({ 
      url: href, 

      datatype: "json", 
      success: function(msg) { 
       alert(msg.exista); 
       if (msg.exista == "yes") { 
        alert('ai aplicat'); 
       } 
       if (msg.aplicat == "yes") { 
        $('#modal_succes').modal('show'); 
       } 
      }, 
     }); 
    }); 
}); 

enter image description here

도 여기에 JSON을

<?php 

$id_c=$_GET['id_c']; 
$id_j=$_GET['id_j']; 

$stmt=$dbh->prepare("SELECT * FROM Aplicatii where id_c=:id_c and id_j=:id_j"); 
$stmt->bindParam(":id_c",$id_c); 
$stmt->bindParam("id_j",$id_j); 
$stmt->execute(); 
if($row=$stmt->fetch()) 
{ 
    $arr = array('exista' => 'yes'); 
    echo json_encode($arr); 
} 
else 
{ 
$stmt=$dbh->prepare("INSERT INTO Aplicatii (id_c,id_j) VALUES (:id_c,:id_j)"); 
$stmt->bindParam(":id_c",$id_c); 
$stmt->bindParam("id_j",$id_j); 
$stmt->execute(); 
$arr = array('aplicat' => 'yes'); 
    echo json_encode($arr); 
} 
?> 

그리고 console.log의 응답을 반환 PHP 코드입니다 :

{"exista":"yes"} 
+0

'을 console.log (MSG) 무엇을 않습니다 구문 분석하는 것입니다? – eisbehr

+0

'{ "exista": "yes"}' – chris227

+0

그래서 '객체'가 아닌'문자열 '을 반환합니까? 그렇다면'msg.exista'는'undefined '가되어야합니다. – eisbehr

답변

2

그것이 objectconsole.log(msg) 반환 {"exista":"yes"} 아니다 , 그것은 string입니다. 따라서 msg.exista과 같은 속성에 액세스하려고 시도하면 undefined이 반환됩니다.

AJAX 요청에서 dataType을 잘못 설정하면이 예는 올바르게 JSON으로 설정됩니다.

문제는 PHP 측에서이므로 Content-Typeheaders 응답에 추가해야합니다. `반환; 옆

header("Content-Type: application/json"); 

header("Content-Type: application/json"); 
+1

답변을 추가해 주셔서 감사합니다. – shivgre

0

이 오류를 해결하는 또 다른 방법은 아약스 응답

msg = JSON.parse(msg);