douba2011 2015-12-25 23:35
浏览 85

AJAX请求返回null

I have the following PHP:

<?php

 $get_messages = mysqli_query($mysqli, "SELECT * FROM messages");

 $messages = array();

 while ( $row = mysqli_fetch_array($get_messages)){

      $messages[] = array( 'name' => $row['name'], 'message' => $row['message']);
 }

 $json = json_encode($messages);
 echo $json;

?>

Which successfully echo the following JSON:

     [{"name":"Ernest","message":"hello"},{"name":"Ernest","message":"hello"},{"name":"john","message":"yes"},{"name":"Diana","message":"I know
"},{"name":"fgafg","message":"fgehfegfvg"},{"name":"fgafg","message":"fgehfegfvg"},{"name":"fgafg","message":"fgehfegfvg"},{"name":"gsfvgx","message":"fbhfxvcz"},{"name":"argttrhjyrbsgdzdc","message":"ahjtgfrdcvdfsevb"}] 

Then I have this JS:

$(document).ready(function(){

  $.ajax({
     url: 'retrieve.php',
     dataType: 'json',
     success: function (response) {
       alert(response[3]);
     }
   });
});

which alerts undefined.

What is the issue here ? Your help will be appreciated.

NOTE: If I change the alert to alert(response[3].name); or alert(response[3][name]); the alert window does not even show up to the party

  • 写回答

2条回答 默认 最新

  • dpl22899 2015-12-25 23:45
    关注

    response is an array of items with name and message properties. So you should basically loop through the items and access it.

    You need to make sure that your ajax call is hitting the success handler. May be add an error handler to verify it.

    success: function (response) {
    
       $.each(response,function(a,b){
         alert(b.name);
         alert(b.message);
       });       
    
     },
     error : function(a,b,c){
        alert("error");
        alert(c);
     }
    

    Here is a working sample of iterating the array.

    Also, If there are any other script error in your page, it won't work. So make sure you don't have any other script error. You can verify it by checking your browser console.

    评论

报告相同问题?

悬赏问题

  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入