通过ajax获得json并解析

约定不等于承诺〃 2023-07-17 11:29 128阅读 0赞

一、在开始前做一些说明

虽然json方式和xml方式可以达到相同的效果,但是在现在json使用更多一些,因为大多数的语言都有对应的json的接口,并且json比xml更简单一点。介绍一些json的函数。

JSON.parse(字符串)可以把JSON字符串转化为对象
JSON.stringify(对象)可以把对象转化为JSON字符串

  1. var JSONo1='{"uname":"李明","age":"20","gender":"male"}'; //必须是字符串,且里面的内容必须用双引号(单引号不行)
  2. console.log(JSONo1); //字符串
  3. console.log(JSON.parse(JSONo1)); //这个是一个对象
  4. console.log(JSON.stringify(JSON.parse(JSONo1))); //字符串
  5. var JSONo2='["soccer","basketball"]';
  6. console.log(JSONo2); //字符串
  7. console.log(JSON.parse(JSONo2)); //数组
  8. console.log(JSON.stringify(JSON.parse(JSONo2))); //字符串
  9. var JSONo3='{"uname":"李明","age":"20","gender":"male","hobbies":["soccer","basketball","baseball"]}';
  10. console.log(JSONo3); //字符串
  11. console.log(JSON.parse(JSONo3)); //对象
  12. console.log(JSON.stringify(JSON.parse(JSONo3)));//字符串
  13. var JSONo4='["soccer","basketball",{"uname":"李明","age":"20","gender":"male"}]';
  14. console.log(JSONo4); //字符串
  15. console.log(JSON.parse(JSONo4)); //数组
  16. console.log(JSON.stringify(JSON.parse(JSONo4)));//字符串
  17. var dom=$("<div>你好</div>") //把字符串转为jQuery对象

二、具体实现

json文件

  1. {
  2. "uname":"李明",
  3. "age":"20",
  4. "gender":"male",
  5. "hobbies":["soccer","basketball","baseball"]
  6. }

php文件

  1. <?php
  2. header('Content-type:application/json','charset=utf-8'); //告诉浏览器传回来的数据是json类型
  3. $json=file_get_contents('./aaa.json'); //读取json文件
  4. echo $json; //输出字符串

html文件

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Document</title>
  6. </head>
  7. <body>
  8. <button>点我</button>
  9. <script>
  10. var btn=document.querySelector('button');
  11. btn.addEventListener('click',function () {
  12. var xhr=new XMLHttpRequest(); //创建异步对象
  13. xhr.open('get','test03.php');
  14. xhr.send(null);
  15. xhr.addEventListener('readystatechange',function () {
  16. if (xhr.status==200&&xhr.readyState==4){
  17. var o=JSON.parse(xhr.responseText); //转化为对象
  18. console.log(o.uname); //使用对象的方法去得到结果
  19. console.log(o['age']);
  20. console.log(o.gender);
  21. console.log(o.hobbies);
  22. }
  23. })
  24. });
  25. </script>
  26. </body>
  27. </html>

本文只用于个人学习和记录

发表评论

表情:
评论列表 (有 0 条评论,128人围观)

还没有评论,来说两句吧...

相关阅读

    相关 unity请求json数据

    unity3d在跟.net进行http通信的时候,最常见的就是表单数据的提交请求了,但服务器端会返回一坨json数据,这就要求我们在unity中进行json数据的处理了,一般u

    相关 JSON

        [ JSON 使用讲解 ][JSON _]这篇文章讲解了,JSON的介绍以及使用GSON解析。今天,我们就在Android项目中使用两种方式解析JSON数据。如果你对J