javascript
  • php
  • angularjs
  • json
  • 2017-03-17 85 views 1 likes 
    1

    我有一個字典的web應用程序的PHP的API,意外標記在位置39

    $outp = ""; 
    
    while($rs = $result->fetch_array(MYSQLI_ASSOC)) { 
        if ($outp != "") {$outp .= ",";} 
        $outp .= '{"WORD":"' . $rs["word"] . '",'; 
        $outp .= '"MEANING":"' . $rs["definition"]  . '"}'; 
    } 
    $outp ='{"records":['.$outp.']}'; 
    $conn->close(); 
    
    echo($outp); 
    
    } 
    else 
    { 
    
    
    } 
    ?> 
    

    並在angularJS側的解析函數如下:

    $scope.counter = function() { 
            console.log(JSON.stringify(response)); 
    
        if($scope.name) { 
         $http.get("http://localhost/dictionary/API/search.php?qr="+$scope.name) 
          .then(function (response) { 
           console.log(JSON.stringify(response.records)); 
          if(response.data.records=="") { 
           queryRes = response.data.records ; 
           $scope.word = ""; 
           $scope.meaning = "" 
          } else { 
    
           queryRes = response.data.records ; 
           $scope.word = queryRes[0].WORD; 
           $scope.meaning = queryRes[0].MEANING; 
          } 
    
        }); 
    
        } 
    
    } 
    

    沒有php api返回單元素數組JSON時出錯如下

    {"records":[{"WORD":"Net","MEANING":"വല"}]} 
    

    但是當php返回數組發言:喜歡,

    {"records":[{"WORD": "End","MEANING": "അറുതി 
    "},{"WORD": "End","MEANING": "അവസാനം 
    "},{"WORD": "End","MEANING": "അതിര്‌ 
    "},{"WORD": "End","MEANING": "സീമ 
    "},{"WORD": "End","MEANING": "പരിസമാപ്‌തി 
    "},{"WORD": "End","MEANING": "അവസാനഘട്ടം 
    "},{"WORD": "End","MEANING": "മരണം 
    "}]} 
    

    得到錯誤這樣

    Unexpected token in JSON at position 39 at JSON.parse (<anonymous>) 
    

    我認爲JSON對象操作是有一些問題。

    +0

    您可以print_out您在js中收到的字符串,並將其粘貼到此處http://json.parser.online.fr/以檢查問題出在哪裏。 – user3711105

    +0

    我檢查過它,發現在PHP端有一些JSON操作的問題。現在通過使用ryan的答案解決。 –

    回答

    0

    不要通過字符串連接構建JSON;使用json_encode

    $records = []; 
    
    while($rs = $result->fetch_array(MYSQLI_ASSOC)) { 
        $records[] = [ 
         'WORD' => $rs["word"], 
         'MEANING' => $rs["definition"], 
        ]; 
    } 
    $conn->close(); 
    
    echo json_encode(['records' => $records]); 
    
    +0

    謝謝!這是問題! –

    相關問題