2015-04-01 109 views
0

的JSON我的PHP返回的是:jQuery的Ajax 「的語法錯誤:輸入意外結束」 關於有效的JSON

{ 「成功」:0, 「消息」: 「錯誤:沒有ENTITYID過去了!」}

仍然我的JavaScript告訴我「SyntaxError:意外的輸入結束」。

PHP:

... 

    //check if an image id was passed for removal in the POST data 
    if (isset($_POST["entityId"])) { 
     $entityId = $_POST["entityId"]; 
    } 
    else { 
     //setup response json 
     $resp = array(); 
     $resp['success'] = 0; 
     $resp['message'] = "Error: No entityId passed!"; 

     header('Content-Type: application/json'); 
     echo json_encode($resp); 
    } 

    ... 

JS:

   // send xhr request 
      $.ajax({ 
       dataType: 'json', 
       type: $theForm.attr('method'), 
       url: $theForm.attr('action'), 
       data: $theForm.serialize(), 
       success: function(data) { 
        //backend returns a json with variable success either true or false. 
        resp = data; 
        if(resp.success == 1) { 
         //render gallery anew 
        } 
        else { 
         console.log(data); 
         if (data.message) { 
          $(self).find('.VanillaGallery-overlayContentWrapper').html(data.message);  
         } 
         else { 
          $(self).find('.VanillaGallery-overlayContentWrapper').html('Oops! Något gick fel, felmeddelande saknas dock.');  
         } 
        } 

       }, 
       error: function(xhr, status, text) { 
        $(self).find('.VanillaGallery-overlayContentWrapper').html('Oops! Något gick fel...<br />'+text); 
       } 
      }); 

很奇怪。

標頭看起來像這樣通過Ajax:

Connection:Keep-Alive 
Content-Length:0 
Content-Type:text/html 
Date:Wed, 01 Apr 2015 17:48:26 GMT 
Keep-Alive:timeout=5, max=97 
Server:Apache/2.2.25 (Unix) mod_ssl/2.2.25 OpenSSL/0.9.8zc DAV/2 PHP/5.5.3 
X-Pad:avoid browser bug 
X-Powered-By:PHP/5.5.3 

並通過此我的頭取決於如果該請求被通過AJAX或作爲直接在瀏覽器(不通過AJAX)純單獨的請求作出不同直接從瀏覽器的地址欄中:

Connection:Keep-Alive 
Content-Length:52 
Content-Type:application/json 
Date:Wed, 01 Apr 2015 17:42:23 GMT 
Keep-Alive:timeout=5, max=100 
Server:Apache/2.2.25 (Unix) mod_ssl/2.2.25 OpenSSL/0.9.8zc DAV/2 PHP/5.5.3 
X-Powered-By:PHP/5.5.3 
+2

你檢查過的開發工具,以驗證HTTP響應真的看起來像什麼,你認爲它看起來喜歡? – Pointy 2015-04-01 15:28:30

+0

難道我的本地主機(Apache MAC,MAMP)沒有配置爲給出適當的JSON響應 – 2015-04-01 17:28:15

+0

我在Chrome中的網絡日誌說'application/json'是否意味着服務器(本地主機)提供了正確的json響應? – 2015-04-01 17:43:25

回答

1

好吧,所以很明顯,一旦你用新鮮的眼光看着它...在ajax請求中傳遞一個entityId(從表單數據不顯示的示例代碼中不明顯...),因此上面的PHP代碼中的第一個IF條件評估爲true。在這一節中,沒有輸出,也沒有任何回聲。這就是爲什麼我得到「意想不到的投入結束」。

而對於通過在瀏覽器地址欄中直接運行來測試它,這種方式PHP當然會出現在我上面的PHP代碼的else-bracket中,並且實際上給出了響應,因爲根本沒有POST數據做這樣...

抱歉佔用您的時間,有時一個是太累了......

0

SyntaxError: Unexpected end of input它通常涉及到一些錯誤/錯字在JS(甚至是PHP),順便說一句你的代碼,獨立,工作正常。你應該檢查其餘的......也許你錯過了某個地方的支架或分號。