2017-06-15 19 views
2

我收到以下錯誤。我不知道我在哪裏得到JSON中的'符號。我已經加倍檢查並確定PHP的json_encode函數不會在第一個位置添加'符號。jQuery在JSON中的意外令牌有效輸入

我已經看到了StackOverflow中的其他問題和解決方案,並且無法在Google中找到針對此特定場景的任何其他解決方案。

SyntaxError: Unexpected token ' in JSON at position 0 
    at parse (<anonymous>) 
    at e.parseJSON (jquery-migrate.min.js:2) 
    at fn (jquery.min.js:6) 
    at k (jquery.min.js:6) 
    at XMLHttpRequest.<anonymous> (jquery.min.js:6) 

下面是生成JSON字符串的PHP代碼。

$info = Embed\Embed::create($videoUrl); 

$result = array(); 

$result['title'] = $info->title; 
$result['desciption'] = $info->description; 
$result['type'] = $info->type; 
$result['tags'] = $info->tags; 
$result['provider'] = $info->providerName; 

echo json_encode($result,true); 

下面是jQuery用來做一個post操作。

$(document).ready(function() { 

    $("#videoUrl").blur(function (event) { 

     if ($(this).val() != '') { 

      $.ajax({ 
       type: 'POST', 
       url: '/url-here', 
       dataType: 'json', 
       data: { 
        "value": $(this).val() 
       }, 
       success: function (msg) { 
        alert("Data Saved: " + msg); 
       }, 
       error: function (XMLHttpRequest, textStatus, errorThrown) { 
        console.log(errorThrown.message); 
       } 
      }) 
     } 

    }); 

}); 

提供了Chrome控制檯中的示例響應供您參考。

'{"title":"Inside of big gold mine in Africa. How it works. Documentary.","desciption":"Deepest mine in Africa.","type":"video","tags":["Megastructures","mine","gold","deepest mine","documentary","Deepest","how it works"],"provider":"YouTube"} 

編輯:

按照要求,我分享了整個PHP代碼。

public function getVideoDetails() { 
    OW::getResponse()->clearHeaders(); 
    OW::getResponse()->setHeader('Content-Type', 'application/json; charset=utf-8'); 

    $videoUrl = $_POST['value']; 

    $info = Embed\Embed::create($videoUrl); 

    $result = array(); 

    $result['title'] = $info->title; 
    $result['description'] = $info->description; 
    $result['type'] = $info->type; 
    $result['tags'] = $info->tags; 
    //$result['image'] = $info->image; 
    $result['provider'] = $info->providerName; 

    echo json_encode($result, true); 

    OW::getResponse() - > sendHeaders(); 
    exit; 
} 
+0

刪除'''''''''''''' – guradio

+0

@guradio:如果您不介意可以指向我哪一行?我找不到'{「文字 – Purus

+0

''{」title「:」o ....' – guradio

回答

2

在PHP的響應意外的前導字符的一個常見原因是,在任何附帶/涉及的PHP腳本的<?php前一個字符。