2015-03-02 107 views
0

流程:主頁 - > php上的ajax請求(tester.php) - > json信息返回主頁面。Ajax調用php - 未定義的索引錯誤

我無法找到解決此錯誤的方法。由於

Ajax調用

$.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]; 
         }); 
       }); 

PHP的:(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]; 
       } 
+3

在成功參數爲什麼你再次調用$ getJSON? – 2015-03-02 20:18:53

+0

您的'成功'函數缺少關閉'}' – mhall 2015-03-02 20:24:01

+1

是的錯誤發生,因爲您使用$ .getJSON發送GET請求到tester.php。在第二個不必要的請求中沒有可用的POST變量 – NaN 2015-03-02 20:24:51

回答

0

的信息,你想使用已經由AJAX調用返回的getJSON得到,所以你可以簡單地檢索來自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]; 
      }; 
     }); 
+0

修復了未定義的索引,但是data [0] =='[',data [1] =='「'。任何想法爲什麼? – Johnxl 2015-03-02 20:35:36

+0

你可以在成功回調中放置一個'console.log(data);' ? – 2015-03-02 20:42:07

+0

結果:data == [「43.66203460000001」,「 - 79.42503199999999」,「2015」,「2015」] data [0] == [,data [1] ==「,data [2] == 4,數據[3] == 3.我如何取字符串而不是字符 – Johnxl 2015-03-02 20:51:43