接收JSON解析错误在AJAX调用 [英] Receiving JSON Parse Error During AJAX Call

查看:151
本文介绍了接收JSON解析错误在AJAX调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个是创造我的JSON需要我的web应用程序的PHP脚本。我使用jQuery的Ajax功能来从所创建的JSON我的PHP页面的JSON。我发现一个奇怪的怪癖,但。如果我只需运行我的PHP文件中的Web浏览器和输出的JSON,然后我复制到JSON文件名为 myJSON.json 这是与我的Ajax URL电话,我的code工作。但是,如果我直接在URL的Ajax调用链接到我的PHP文件,我得到以下错误: 请求的JSON解析失败 。因此,这里是我的相关PHP code:

 < PHP

$ groupArray =阵列();

//设置JSON文件的开头
$ JSON ='
{
    电子邮件:';

 //循环请求结果
的foreach($ contextIORequest->的getData()为$消息){

  //`date_received`是Unix时间。开始转换这对一个可读的日期,并将其转换成用户的时区
  $ newTZ​​ =新DateTimeZone(美国/芝加哥); //这将根据在生产过程中的用户位置
  $ currentTime的=新的日期时间();
  $ currentTime的=日期时间:: createFromFormat(U,$消息['date_received']);
  $ currentTime-> setTimezone($ newTZ​​);
  $ formattedDateReceived = $ currentTime->格式('FĴ,Y');

  // JSON的结构是按日期(集团)主办。每一个独特的日期将被放置在自己的组中的JSON文件。因此,我们需要检查的日期已经在$ groupArray。如果是,则我们简单地将电子邮件数据添加到当前日期组。如果日期是不是已经在$ groupArray,那么我们就需要创建一个新组和电子邮件数据添加到新组。
  如果(!in_array($ formattedDateReceived,$ groupArray)){

    //该日期是尚未在$ groupArray

    //检查,如果这是第一批被添加到$ groupArray。如果是,第一组中加入需要不同格式比将添加所有其他组
    如果(计数($ groupArray)== 0){

      //这是被添加的第一组
      $ JSON。='{
            群:'$ formattedDateReceived。'
            清单:[';

    } 其他 {

      //这不是第一组被添加。关闭previous集团和排行榜的对象,然后创建新的组和表对象。

      //在结束前的previous集团和排行榜的对象,我们需要删除后面的逗号,从最后的名单的项目在previous组
      $ JSON = RTRIM($ JSON,,);

      //']'被关闭previous名单的对象。 },正在关闭previous组对象
      $ JSON。=']
        },{
            群:'$ formattedDateReceived。'
            清单:[';

    }

    //现在我们需要把这个日期添加到$ groupArray
    $ groupArray [] = $ formattedDateReceived;


    //电子邮件的身体就不能有转义引号或apostrophies。它也不能有换行符或单词之间的多个空格。
    $身体=和addslashes($信息[身体] [0] ['内容']); //脱报价和apostrophies
    $身体= str_replace函数(阵列(\ r \ N,\ N),,$机构); //删除所有换行符导致身体的字符串是所有在同一行
    $ newBody = preg_replace('!\ S +','',$机构); //删除单词之间的多个空格

    //添加邮件到JSON结构
    $ JSON。='
    {
      ID:,$消息['MESSAGE_ID'。'
      主题:'.addslashes($消息['主题'])。'
      到:大卫·内斯特,简·史密斯],
      身:'$ newBody。'
      时间:'$ formattedDateReceived。'
      日期时间:'$ formattedDateReceived。'
      从:,$消息['地址'] ['从'] ['名称']。'
      DP:资产/ IMG /型材/ avatar.jpg
      D pretina:资产/ IMG /型材/ avatar2x.jpg
    };

//回声< H1>新建集团及LT; / H1>中;
//回声日期:$消息['date_received']($ formattedString)\ N'LT; BR>中;
//回声从:。$消息['从'] ['地址'] [电子邮件]\ N'LT; BR>中;
//回声主题:$消息['主题']\ N'LT; BR>中;
//回声螺纹尺寸:$消息['thread_size']\ N'LT; BR>中;
//回声消息ID:$消息['MESSAGE_ID']\ N'LT; BR>中;
//回声标志:。$消息['国旗'] [0]\ N'LT; BR>中;

  } 其他 {

    //该日期是已经在$ groupArray

    //电子邮件的身体就不能有转义引号或apostrophies。它也不能有换行符或单词之间的多个空格。
    $身体=和addslashes($信息[身体] [0] ['内容']); //脱报价和apostrophies
    $身体= str_replace函数(阵列(\ r \ N,\ N),,$机构); //删除所有换行符导致身体的字符串是所有在同一行
    $ newBody = preg_replace('!\ S +','',$机构); //删除单词之间的多个空格

    //添加邮件到JSON结构
    $ JSON。='
    {
      ID:,$消息['MESSAGE_ID'。'
      主题:'.addslashes($消息['主题'])。'
      到:大卫·内斯特,简·史密斯],
      身:'$ newBody。'
      时间:'$ formattedDateReceived。'
      日期时间:'$ formattedDateReceived。'
      从:,$消息['地址'] ['从'] ['名称']。'
      DP:资产/ IMG /型材/ avatar.jpg
      D pretina:资产/ IMG /型材/ avatar2x.jpg
    };

  }
} //结束foreach循环

//关闭前的最后集团和排行榜的对象,我们需要删除后面的逗号,从最后的名单项中的最后一个组
$ JSON = RTRIM($ JSON,,);

//完成JSON结构
$ JSON。=']
        }
    ]
};

//输出的JSON
file_put_contents('emails.json',$ JSON);
标题(内容类型:应用程序/ JSON;字符集= UTF-8);
回声$ JSON;

?>
 

所以,如果我在Web浏览器中运行这个PHP文件,它输出的JSON。然后我复制并粘贴JSON成JSON文件。然后我我的AJAX调用链接到JSON文件,一切都正确分析。 但是我需要链接到,在我的AJAX调用创建JSON的PHP文件。但是,当我这样做,我得到即使它是完全一样的code我复制并粘贴在作品完美我的JSON文件解析错误。我真的难倒就这一个。这是我的有关AJAX code,以及:

  $。阿贾克斯({
    数据类型:JSON,
    网址:创造json.php
    成功:功能(数据){

        $每个(data.emails,功能(我){
            VAR OBJ = data.emails [I]
            VAR列表= obj.list;

            $每个(列表中,函数(J){
                变量$此=列表[J]。
                VAR ID = $ this.id;
            });

        });

    },
    错误:函数(jqXHR,异常){
        如果(jqXHR.status === 0){
            警报(在不连接\ñ检查网络。);
        }否则,如果(jqXHR.status == 404){
            警报('请求的页面未找到[404]');
        }否则,如果(jqXHR.status == 500){
            警报(内部服务器错误[500]。');
        }否则,如果(例外===parsererror'){
            警报('要求JSON解析失败了。');
        }否则,如果(例外==='超时'){
            警报('超时错误。');
        }否则,如果(例外==='中止'){
            警报(Ajax请求中止。');
        } 其他 {
            警报(未捕获的错误。\ n'+ jqXHR.responseText);
        }
    }
}
 

解决方案

而不是试图从头开始创建一个JSON字符串,使用关联数组(键=>值)建立自己的数据结构,只是 json_en code(),它会为您节省格式化了不少麻烦。

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

修订code

  $ groupArray =阵列();

$ JSON =阵列('邮件'=>阵列());

的foreach($ contextIORequest->的getData()为$消息){

  $ newTZ​​ =新DateTimeZone(美国/芝加哥);
  $ currentTime的=新的日期时间();
  $ currentTime的=日期时间:: createFromFormat(U,$消息['date_received']);
  $ currentTime-> setTimezone($ newTZ​​);
  $ formattedDateReceived = $ currentTime->格式('FĴ,Y');

  如果(!in_array($ formattedDateReceived,$ groupArray)){
      array_push($ JSON ['邮件'],
          阵列(
               '组'=> $ formattedDateReceived,
               名单'=>阵列()
          )
      );
      $ groupArray [] = $ formattedDateReceived;
  }

  $身体= str_replace函数(阵列(\ r \ N,\ N),,$消息['身体'] [0] ['内容']);
  $ newBody = preg_replace('!\ S +','',$机构);

  array_push($ JSON ['邮件'] [array_search($ formattedDateReceived,$ groupArray)] ['名单'],
      阵列(
        'ID'=> $消息['MESSAGE_ID'],
        '主题'=>和addslashes($消息['主题']),
        '到'=>阵列(我),
        身体=> $ newBody,
        '时间'=> $ formattedDateReceived,
        '日期时间'=> $ formattedDateReceived,
        从'=> $消息['地址'] ['从'] ['名称'],
        'DP'=> 资产/ IMG /型材/ avatar.jpg
        'D pretina'=> 资产/ IMG /型材/ avatar2x.jpg
      )
  );

} //结束foreach循环

//输出的JSON
标题(内容类型:应用程序/ JSON);
回声json_en code($ JSON);
 

I have a PHP script that is creating my JSON needed for my web app. I am using jQuery's Ajax capabilities to fetch the JSON from my PHP page that is creating the JSON. I am finding a weird quirk though. If I simply run my PHP file in the web browser and output the JSON and then I copy that JSON into a file named myJSON.json which is linked to my Ajax URL call, my code works. However, If I link directly to my PHP file in the Ajax URL call, I get the following error: Requested JSON parse failed. So here is my relevant PHP Code:

<?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;

?>

So if I run this PHP file in my web browser, it outputs the JSON. I then copied and pasted the JSON into a JSON file. I then link my AJAX call to the JSON file and everything is parsed correctly. But I need to link to the PHP file that creates the JSON in my AJAX call. However, when I do this, I get a parse error even though it is the exact same code I copied and pasted in my JSON file that works perfectly. I am really stumped on this one. Here is my relevant AJAX code as well:

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

解决方案

Instead of trying to create a JSON string from scratch, build your data structure using associative arrays (key => value), and just json_encode() it, it will save you a lot of trouble on formatting.

Also note that this function escapes strings for you.

Revised code

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

这篇关于接收JSON解析错误在AJAX调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆