Ajax调用php - 未定义的索引错误

时间:2015-03-02 20:13:36

标签: javascript php jquery ajax

流程:主页 - > php上的ajax请求(tester.php) - > json信息回到主页。

我找不到解决此错误的方法。感谢

ajax call

$.ajax({
                url : "tester.php",
                type : "POST",
                //dataType : 'json',
                data : {
                    'lat':lat,
                    'lng':lng,
                    'year1':year1,
                    'month1':month1,
                    'day1':day1,
                    'year2':year2,
                    'month2':month2,
                    'day2':day2,
                    'category':category
                },
                 success: function(data)
                {
                    $.getJSON('tester.php',function(cost)
                        {
                            document.getElementById('userdensity').innerHTML = cost[0]+","+cost[1];
                            document.getElementById('advertising_cost').innerHTML = cost[2]+","+cost[3];
                        });
                });

腓:(tester.php):

<?
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$year1 = $_POST['year1'];
$year2 = $_POST['year2'];

$cost = array($lat,$lng,$year1,$year2);
echo json_encode($cost);

?>

错误:

[02-Mar-2015 21:02:35 Europe/Berlin] PHP Notice:  Undefined index: lat in /Users/tester.php on line 2
[02-Mar-2015 21:02:35 Europe/Berlin] PHP Notice:  Undefined index: lng in /Users/tester.php on line 3
[02-Mar-2015 21:02:35 Europe/Berlin] PHP Notice:  Undefined index: year1 in /Users/tester.php on line 4
[02-Mar-2015 21:02:35 Europe/Berlin] PHP Notice:  Undefined index: year2 in /Users/tester.php on line 5

不确定错误的位置。我过去做过这个并且进展顺利。

解决方案:将成功更改为:

success: function(data)
                {
                    var info = $.parseJSON(data);
                            document.getElementById('userdensity').innerHTML = info[0]+","+info[1];
                            document.getElementById('advertising_cost').innerHTML = info[2]+","+info[3];
                }

1 个答案:

答案 0 :(得分:0)

您尝试使用getJson获取的信息已经被AJAX调用返回,因此您只需从返回的data变量中检索即可。你可以改写成这样的东西:

 $.ajax({
            url : "tester.php",
            type : "POST",
            //dataType : 'json',
            data : {
                'lat':lat,
                'lng':lng,
                'year1':year1,
                'month1':month1,
                'day1':day1,
                'year2':year2,
                'month2':month2,
                'day2':day2,
                'category':category
            },
             success: function(data){    
                response = $.parseJSON(data);                                       
                document.getElementById('userdensity').innerHTML = response[0]+","+response[1];
                document.getElementById('advertising_cost').innerHTML = response[2]+","+response[3];
            };
        });