jQuery通过Ajax向服务器获取数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zlq_CSDN/article/details/88762164

服务器返回的数据一般分为两种,一种是xml,一种是json

  1. 前端发送Ajax请求
ajax({
    type:"GET",
    url:"10.php",
    data:{},
    timeout:3000,
    success:function (msg) {
        // console.log(msg.responseText);
        //注意:如果要返回xml文件,则我们在前端用responseXML来接收数据  如果是json文件,则需要转换为js对象
        console.log(msg.responseXML);
        // console.log(document);
        console.log(msg.responseXML.querySelector("name"));
        console.log(msg.responseXML.querySelector("age").innerHTML);
    },
    error:function (xhr) {
        console.log(xhr.status);
    }
})
  1. 后端服务器端请求数据
<?php
    //如果结果中有中文,必须在PHP文件顶部设置
    //header("content-type:text/html;charset=utf-8");
    //如果PHP中需要返回xml数据,同样必须在文件顶部设置
    header("content-type:text/xml;charset=utf-8");
    echo file_get_contents("10.xml");
?>
  1. 编写对应的json、xml文件存储数据

    XML属于可扩展标记语言,使用时应注意:

<?xml version="1.0" encoding="UTF-8" ?>
<!-- 注意:xml文件必须以第一句开头,内容必须放在根节点中(根节点随便写) -->
<note>
    <name>zlq</name>
    <age>22</age>
</note>

猜你喜欢

转载自blog.csdn.net/zlq_CSDN/article/details/88762164
今日推荐