doujingke4981
2017-02-08 16:34
浏览 112

为什么jQuery AJAX。 返回值未定义?

A weird thing is happening when I execute a function that "alerts" data from a json. If I specify, like alert(data.name);, the "Alert" returns "Undefined", but if I just put alert(data);, it returns the object like {"id":"1","name":"Erluan"}

This is the function that receives an id to search in the database

function receiveUser(val){
            $.ajax({
               type:"POST",
               url:"../json/userperm/userGrid.php",
               data: 'iduser='+val,
               datatype:"json",
               success: function(data, string, jqXHR){
                    alert(data.name);
               }
            });
}

And this is the userGrid.php

<?php
include('../../config.php');

$user = mysql_query("SELECT * from hospital_".$_SESSION['template'].".users where id = ".$_POST['iduser']." order by name");

$results = array();

while($row = mysql_fetch_array($user))
{
   $results[] = array(
      'id' => $row['id'],
      'name' => $row['name']
   );
}

$json = json_encode($results);

echo $json;
?>

Thank you.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dp19001 2017-02-08 16:52
    已采纳

    Returning JSON from a PHP Script

    Your php script needs the correct header:

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

    It seems JQuery is intrepteing the result as the string {"id":"1","name":"Erluan"}, by having the correct header it should then be parsed as JSON.

    已采纳该答案
    打赏 评论
  • dongyi0114 2017-02-08 18:55

    Have you tried evaluating the ajax response? If not then try to call eval function and then fetch the values.

     success: function(data, string, jqXHR){
                   var res = eval('(' + data+ ')');
                    alert(res.name);
               }
    
    打赏 评论

相关推荐 更多相似问题