2015-04-01 105 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),顺便说一句你的代码,独立,工作正常。你应该检查其余的......也许你错过了某个地方的支架或分号。