2014-09-01 140 views
-1

我創建了一個簡單的PHP腳本。如果您輸入"hello"作爲POST參數name,則應返回錯誤。否則,它應該返回成功。返回值應該出現在DIV中。爲什麼這個php json不工作

但它不工作?爲什麼不?

if(isset($_POST)){ 
    $name = $_POST['name']; 

    if($name == 'hello'){ 
     echo json_encode(array('comment_error' => 'You cant say hello')); 
    } else { 

    } 
    echo json_encode(array('comment_success' => 'awesome! It worked')); 

} 

下面是解析響應的JavaScript:

$.ajax({ 
    type: 'POST', 
    url: 'comment/post.php', 
    data: {name:name}, 
    dataType: 'json', 
    success:function(data){ 
      if(data.comment_error){ 
       alert(data.comment_error); 
      } else { 
       $('div').append(data.comment_success); 
      } 
    } 
}); 
+7

成功代碼在else語句之外? – Ozzy 2014-09-01 13:02:16

+0

你也應該在你的php中設置正確的json內容類型頭文件 – Steve 2014-09-01 13:03:42

+0

也需要var json = $ .parseJSON(data); – 2014-09-01 13:03:48

回答

2

移動的PHP代碼的最後一行到else條件並更改js代碼

data = JSON.parse(data); // add this in your call back 
if(data.comment_error){ 
    alert(data.comment_error); 
} else { 
    $('div').append(data.comment_success); 
} 
+0

當我添加這個時,即時獲得這個。意外的令牌Ø – user3613245 2014-09-01 13:08:27

+0

所以調試它做console.log(數據);返回;數據之前= JSON.parse(data);線,並檢查控制檯,如果有任何錯誤在PHP或您的輸出是否在正確的JSON格式 – kazimt9 2014-09-01 13:10:25

+0

是啊我得到「對象{comment_error:」你不能說你好「}」 – user3613245 2014-09-01 13:14:43

0

檢查if else loop

代碼應該是這樣的

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

if(isset($_POST)){ 
     $name = $_POST['name']; 

     if($name == 'hello'){ 
      echo json_encode(array('comment_error' => 'You cant say hello')); 
     } else { 
      echo json_encode(array('comment_success' => 'awesome! It worked')); 
     } 


    } 
+0

補充說,仍然不會工作。這不是一個JavaScript問題 – user3613245 2014-09-01 13:08:55

+0

你得到的錯誤?你的ajax電話是否工作? – 2014-09-01 13:10:01

2

你必須發送Json頭信頭('Content-Type:application/json');

header('Content-Type: application/json'); 
if(isset($_POST)){ 

    $name = $_POST['name']; 

    if($name == 'hello'){ 
     echo json_encode(array('comment_error' => 'You cant say hello')); 
    } else { 

    } 
    echo json_encode(array('comment_success' => 'awesome! It worked')); 

} 
0

將這個 回波json_encode(陣列( 'comment_success'=> '真棒它的工作!')); 否則裏面是這樣的:

header('Content-Type: application/json'); 
if(isset($_POST)){ 

    $name = $_POST['name']; 

    if($name == 'hello'){ 
     echo json_encode(array('comment_error' => 'You cant say hello')); 
    } else { 
     echo json_encode(array('comment_success' => 'awesome! It worked')); 
    } 

} 

順便說一句。如果您使用免費主機測試您的腳本(如000webhost),則應該知道他們在html中添加了額外的代碼行。如果這樣的話,Ajax不能解析json對象。

這不能被解析:

<!-- Blabla 000webhost free hosting blabla --> 
{"comment_success" : "awesome! It worked"} 
<!-- Blabla 000webhost free hosting blabla --> 

P.S你不需要VAR json = $.parseJSON(data);因爲dataType = 'json'會爲你。我的意思是成功的「數據」已經是一個JSON對象。