热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

jQuery教程分享在AJAX调用期间接收JSON解析错误

我有一个PHP脚本,它正在创建我的Web应用程序所需的JSON。我正在使用jQuery的Ajaxfunction从我创建JSON的PHP页面获取JSON。我发现了一个奇怪的怪癖。如

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

 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("rn","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 "New Group"; // echo "Date: ".$message['date_received']." ($formattedString)n
"; // echo "From: ".$message['addresses']['from']['email']."n
"; // echo "Subject: ".$message['subject']."n
"; // echo "Thread Size: ".$message['thread_size']."n
"; // echo "Message ID: ".$message['message_id']."n
"; // echo "Flags: ".$message['flags'][0]."n
"; } 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("rn","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); } } } 

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

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

    修改后的代码

     $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("rn","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); 

      以上就是jQuery教程分享在AJAX调用期间接收JSON解析错误相关内容,想了解更多jQuery开发(异常处理)及jQuery教程关注(编程笔记)。


      推荐阅读
      • 原文链接:Python:获取“3年前的今天”的日期时间Python:getdatetimefor3yearsagotoday在Python中,如何获取3年前的今天的datetime ... [详细]
      • Go GUIlxn/walk 学习3.菜单栏和工具栏的具体实现
        本文介绍了使用Go语言的GUI库lxn/walk实现菜单栏和工具栏的具体方法,包括消息窗口的产生、文件放置动作响应和提示框的应用。部分代码来自上一篇博客和lxn/walk官方示例。文章提供了学习GUI开发的实际案例和代码示例。 ... [详细]
      • 生成式对抗网络模型综述摘要生成式对抗网络模型(GAN)是基于深度学习的一种强大的生成模型,可以应用于计算机视觉、自然语言处理、半监督学习等重要领域。生成式对抗网络 ... [详细]
      • 云原生边缘计算之KubeEdge简介及功能特点
        本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
      • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
      • IhaveconfiguredanactionforaremotenotificationwhenitarrivestomyiOsapp.Iwanttwodiff ... [详细]
      • CSS3选择器的使用方法详解,提高Web开发效率和精准度
        本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
      • 本文讨论了使用差分约束系统求解House Man跳跃问题的思路与方法。给定一组不同高度,要求从最低点跳跃到最高点,每次跳跃的距离不超过D,并且不能改变给定的顺序。通过建立差分约束系统,将问题转化为图的建立和查询距离的问题。文章详细介绍了建立约束条件的方法,并使用SPFA算法判环并输出结果。同时还讨论了建边方向和跳跃顺序的关系。 ... [详细]
      • sklearn数据集库中的常用数据集类型介绍
        本文介绍了sklearn数据集库中常用的数据集类型,包括玩具数据集和样本生成器。其中详细介绍了波士顿房价数据集,包含了波士顿506处房屋的13种不同特征以及房屋价格,适用于回归任务。 ... [详细]
      • 动量|收益率_基于MT策略的实战分析
        篇首语:本文由编程笔记#小编为大家整理,主要介绍了基于MT策略的实战分析相关的知识,希望对你有一定的参考价值。基于MT策略的实战分析 ... [详细]
      • Answer:Theterm“backslash”isonofthemostincorrectlyusedtermsincomputing.People ... [详细]
      • Spring Boot 中 Java8 LocalDateTime 序列化问题
        LoginController页面如下:publicObjectlogin(@RequestBodyUseruser){returnxxxx ... [详细]
      • 本文由编程笔记#小编为大家整理,主要介绍了php活动日历-获取下一个即将举行的特色活动相关的知识,希望对你有一定的参考价值。 ... [详细]
      • 1.使用通用mapper时实体类的mapper接口(即普通的dao接口)继承了通用mapper接口后,在依赖注入实体类的mapper接口时 ... [详细]
      • 如何在Android中获取当前时间和日期
        如何在Android应用中获取当前时间和日期?#1楼finalCalendarcCalendar.getInstance();intmYearc.get(Calen ... [详细]
      author-avatar
      杨扬洒傻
      这个家伙很懒,什么也没留下!
      PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
      Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有