Получение ошибки анализа JSON во время вызова AJAX

У меня есть PHP-скрипт, который создает мой JSON, необходимый для моего веб-приложения. Я использую возможности jQuery Ajax для извлечения JSON с моей страницы PHP, которая создает JSON. Однако я нахожу странную причуду. Если я просто запустил свой PHP-файл в веб-браузере и myJSON.json JSON, а затем myJSON.json этот JSON в файл с именем myJSON.json связанный с моим URL-адресом Ajax, мой код работает. Однако, если я прямо ссылаюсь на свой PHP-файл в вызове URL-адреса Ajax, я получаю следующую ошибку: Requested JSON parse failed . Итак, вот мой соответствующий PHP-код:

 <?php $groupArray = array(); // Setup the beginning of the json file $json = ' { "emails": ['; // Loop through the request results foreach ($contextIORequest->getData() as $message) { // `date_received` is in Unix time. Begin converting this to a readable date and convert it to the users timezone $newTZ = new DateTimeZone("America/Chicago"); // This will be based on the users location during production $currentTime = new DateTime(); $currentTime = DateTime::createFromFormat('U', $message['date_received']); $currentTime->setTimezone($newTZ); $formattedDateReceived = $currentTime->format('F j, Y'); // The JSON structure is organized by date (group). Each unique date will be placed in its own group in the JSON file. So we need to check if a date is already in the $groupArray. If it is, then we simply add the email data to the current date group. If the date is not already in the $groupArray, then we will need to create a new group and add the email data to the new group. if (!in_array($formattedDateReceived, $groupArray)) { // This date is not yet in the $groupArray // Check if this is the first group being added to the $groupArray. If it is, the first group added requires different formatting than all other groups that will be added if (count($groupArray) == 0) { // This is the first group being added $json .= '{ "group": "'.$formattedDateReceived.'", "list": ['; } else { // This is not the first group being added. Close the previous "group" and "list" objects and then create new "group" and "list" objects. // Before closing the previous "group" and "list" objects, we need to remove the trailing comma ',' from the last "list" item in the previous "group" $json = rtrim($json, ','); // ']' is closing the previous "list" object. '},' is closing the previous "group" object $json .= '] },{ "group": "'.$formattedDateReceived.'", "list": ['; } // Now we need to add this date to the $groupArray $groupArray[] = $formattedDateReceived; // The body of the email cannot have unescaped quotes or apostrophies. It also cannot have line breaks or multiple spaces between words. $body = addslashes($message['body'][0]['content']); // Escapes quotes and apostrophies $body = str_replace(array("\r\n","\n"),"", $body); // Removes all line breaks causing the body string to be all on one line $newBody = preg_replace('!\s+!', ' ', $body); // Remove any multiple spaces between words // Add the email to the JSON structure $json .= ' { "id": "'.$message['message_id'].'", "subject": "'.addslashes($message['subject']).'", "to": ["David Nester", "Jane Smith"], "body": "'.$newBody.'", "time": "'.$formattedDateReceived.'", "datetime" : "'.$formattedDateReceived.'", "from": "'.$message['addresses']['from']['name'].'", "dp": "assets/img/profiles/avatar.jpg", "dpRetina": "assets/img/profiles/avatar2x.jpg" },'; // echo "<h1>New Group</h1>"; // echo "Date: ".$message['date_received']." ($formattedString)\n<br>"; // echo "From: ".$message['addresses']['from']['email']."\n<br>"; // echo "Subject: ".$message['subject']."\n<br>"; // echo "Thread Size: ".$message['thread_size']."\n<br>"; // echo "Message ID: ".$message['message_id']."\n<br>"; // echo "Flags: ".$message['flags'][0]."\n<br>"; } else { // This date is already in the $groupArray // The body of the email cannot have unescaped quotes or apostrophies. It also cannot have line breaks or multiple spaces between words. $body = addslashes($message['body'][0]['content']); // Escapes quotes and apostrophies $body = str_replace(array("\r\n","\n"),"", $body); // Removes all line breaks causing the body string to be all on one line $newBody = preg_replace('!\s+!', ' ', $body); // Remove any multiple spaces between words // Add the email to the JSON structure $json .= ' { "id": "'.$message['message_id'].'", "subject": "'.addslashes($message['subject']).'", "to": ["David Nester", "Jane Smith"], "body": "'.$newBody.'", "time": "'.$formattedDateReceived.'", "datetime" : "'.$formattedDateReceived.'", "from": "'.$message['addresses']['from']['name'].'", "dp": "assets/img/profiles/avatar.jpg", "dpRetina": "assets/img/profiles/avatar2x.jpg" },'; } } // end foreach loop // Before closing the very last "group" and "list" objects, we need to remove the trailing comma ',' from the last "list" item in the last "group" $json = rtrim($json, ','); // Complete the JSON structure $json .= '] } ] }'; // Output the JSON file_put_contents('emails.json', $json); header('Content-type: application/json; charset=utf-8'); echo $json; ?> 

Поэтому, если я запустил этот PHP-файл в своем веб-браузере, он выводит JSON. Затем я скопировал и вставил JSON в файл JSON. Затем я связываю свой вызов AJAX с файлом JSON, и все правильно разбирается. Но мне нужно связать с файлом PHP, который создает JSON в моем вызове AJAX. Однако, когда я это делаю, я получаю ошибку синтаксического анализа, хотя это тот же самый код, который я скопировал и вставил в свой файл JSON, который работает отлично. Я действительно в тупике. Вот мой соответствующий код AJAX:

 $.ajax({ dataType: "json", url: "create-json.php", success: function(data) { $.each(data.emails, function(i) { var obj = data.emails[i]; var list = obj.list; $.each(list, function(j) { var $this = list[j]; var id = $this.id; }); }); }, error: function(jqXHR, exception) { if (jqXHR.status === 0) { alert('Not connect.\n Verify Network.'); } else if (jqXHR.status == 404) { alert('Requested page not found. [404]'); } else if (jqXHR.status == 500) { alert('Internal Server Error [500].'); } else if (exception === 'parsererror') { alert('Requested JSON parse failed.'); } else if (exception === 'timeout') { alert('Time out error.'); } else if (exception === 'abort') { alert('Ajax request aborted.'); } else { alert('Uncaught Error.\n' + jqXHR.responseText); } } }