2016-09-16 62 views
2

你好,我有这个脚本,返回msg undefined。在CONSOL中它返回jsondata,但是当我做出警报或当我试图验证它时,它不起作用。ajax成功:函数(味精)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

也在这里是PHP代码,返回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响应:

{"exista":"yes"} 
+0

是什么'的console.log(味精);'返回? – eisbehr

+0

'{“exista”:“yes”}' – chris227

+0

所以它返回一个'string'而不是'object'?然后'msg.exista'必须是'undefined'。 – eisbehr

回答

2

console.log(msg)回报{"exista":"yes"}它不是一个object ,它是一个string。所以试图访问一个属性,如​​,将返回undefined

当您在您的AJAX请求中设置了错误的dataType时,可能会发生这种情况,在您的示例中正确设置为JSON

所以问题在于PHP方面,您需要将正确的Content-Type添加到响应headers

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

感谢您添加答案 – shivgre

0

一边

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

另一种方式来解决这个错误是解析你的Ajax响应

msg = JSON.parse(msg);