jquery load 的高级应用

本文介绍如何利用jQuery的load方法加载本地HTML文件及JSON数据,并解析这些数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.运用load 载入公共文件(比如 网页中的公共head.html, top.html)或者公用的 html 模块

比如base.html 中的内容

<div style="width:100px;height:100px">
    <p  id="#p1">这是公共部分2</p>
    <p  id="#p2">这是公共部分1</p>
<div>

在main.html 中引用base.html 内容如下

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>我的css 案例</title>
        <link rel="stylesheet" type="text/css" href="//cdn.bootcss.com/normalize/4.2.0/normalize.css"/>
        <link rel="stylesheet" type="text/css" href="css/main.css"/>
        <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
        <script type="text/javascript" src="js/script.js" ></script>
    </head>
    <body>
        <div id="id1" style="width:200px;height:200px">
        <div>
    </body>
    <script>
    //载入公用节点模板
        $(function(){
            $("#id1").load("base.html");
        });
    </script>
    <html>
  1. 通过load 方法 加载本地的json 数据
    比如 base.json 中的数据
{"id":"1","age":"18","name":"zhangshan"}

main.html中的内容

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>我的css 案例</title>
        <link rel="stylesheet" type="text/css" href="//cdn.bootcss.com/normalize/4.2.0/normalize.css"/>
        <link rel="stylesheet" type="text/css" href="css/main.css"/>
        <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
        <script type="text/javascript" src="js/script.js" ></script>
    </head>
    <body>
        <div id="id1" style="width:200px;height:200px"><div>
    </body>
    <script>
        $(function(){
            // 载入json 文件
            $("#id1").load("base.json",function(responseTxt,statusTxt,xhr){
                // 获取json数据
                  if(statusTxt=="success")
                     $json=$("#id1").text();
                     $obj=$.parseJSON($json);
                     $.each($obj,function(key,value){
                        alert("key-"+key+"  value-"+value);
                     });

                    if(statusTxt=="error")
                      alert("Error: "+xhr.status+": "+xhr.statusText);
                  });
            });
    </script>
    <html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值