在AJAX调用期间接收JSON解析错误

时间:2015-02-03 21:55:37

标签: javascript php jquery ajax json

我有一个PHP脚本,用于创建我的Web应用程序所需的JSON。我正在使用jQuery的Ajax功能从我创建JSON的PHP页面获取JSON。我发现了一个奇怪的怪癖。如果我只是在Web浏览器中运行我的PHP文件并输出JSON,然后将该JSON复制到一个名为myJSON.json的文件中,该文件链接到我的Ajax URL调用,我的代码就可以了。但是,如果我在Ajax URL调用中直接链接到我的PHP文件,则会收到以下错误: 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;

?>

因此,如果我在Web浏览器中运行此PHP文件,则会输出JSON。然后我将JSON复制并粘贴到JSON文件中。然后我将我的AJAX调用链接到JSON文件,所有内容都被正确解析。 但是我需要链接到在我的AJAX调用中创建JSON的PHP文件。但是,当我这样做时,我得到一个解析错误,即使它是我复制并粘贴在我的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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

不是尝试从头开始创建JSON字符串,而是使用关联数组(key =&gt; value)构建数据结构,而只是json_encode()它,它将为您节省格式化方面的许多麻烦。< / p>

另请注意,此函数会为您转义字符串。

修改后的代码

$groupArray = array();

$json = array( 'emails' => array() );

foreach ($contextIORequest->getData() as $message) {

  $newTZ = new DateTimeZone("America/Chicago");
  $currentTime = new DateTime();
  $currentTime = DateTime::createFromFormat('U', $message['date_received']);
  $currentTime->setTimezone($newTZ);
  $formattedDateReceived = $currentTime->format('F j, Y');

  if (!in_array($formattedDateReceived, $groupArray)) {
      array_push( $json['emails'],
          array(
               'group' => $formattedDateReceived,
               'list' => array()
          )
      );
      $groupArray[] = $formattedDateReceived;
  }

  $body = str_replace(array("\r\n","\n"),"", $message['body'][0]['content']);
  $newBody = preg_replace('!\s+!', ' ', $body);

  array_push($json['emails'][array_search($formattedDateReceived,$groupArray)]['list'],
      array(
        'id' => $message['message_id'],
        'subject'=> addslashes($message['subject']),
        'to' => array("Me"),
        '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

// Output the JSON
header('Content-Type: application/json');
echo json_encode($json);