jquery ajax "SyntaxError: Unexpected end of input" on valid JSON

jquery ajax "SyntaxError: Unexpected end of input" on valid JSON

我的PHP返回的JSON是:

{"success":0,"message":"Error: No entityId passed!"}

我的 javascript 仍然告诉我 "SyntaxError: Unexpected end of input"。

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);
                 }
             });

很奇怪。我的 headers 有所不同,具体取决于请求是通过 ajax 还是直接在浏览器中作为单独的请求(而不是通过 ajax):

headers 通过 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

然后直接从浏览器地址栏通过这个:

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

SyntaxError: Unexpected end of input 它通常与 JS 中的某些 mistake/typo(甚至 PHP)相关,顺便说一句,您的代码,独立的,工作正常。您应该检查其余部分...也许您在某处遗漏了括号或分号。

好的,所以一旦你用新的眼光来看它就很明显了...在 ajax 请求中传递了一个 entityId(从示例代码中看不出来,因为没有显示表单数据.. .) 因此上面 PHP 代码中的第一个 IF 条件的计算结果为真。在那个子句中,没有输出,没有任何形式的回声。这就是为什么我得到 "unexpected end of input".

至于直接在浏览器地址栏中通过 运行 进行测试,这样 PHP 当然会落在上面我的 PHP 代码的 else 括号中,并且实际上给出一个响应,因为根本没有 POST-data 那样做...

抱歉打扰了,有时候太累了...