js中的Ajax

Css代码:

<p id="p1">修改文档文本内容</p>

<button id="btn">点击修改</button>

 

Js代码:

//给按钮绑定点击事件

$("#btn").click(function () {

 

1、创建XMLHttpRequest对象

var xhr;

 

if (window.XMLHttpRequest) {

    // 兼容IE7以上的浏览器执行的代码

        xhr = new XMLHttpRequest();

} else {

// 兼容IE6, IE5 浏览器执行代码

        xhr = new ActiveXObject("Microsoft.XMLHTTP");

}

 

2、向服务器发送请求,设置请求参数

        //xhr.open(method,url,async);

        //open()规定请求的类型,URL以及是否异步处理

        //method:请求方式 GET/POST

        //url:请求路径

        //async:是否异步 默认:true(异步)   false(同步)

xhr.open("POST", "/Jquery/changeTxt");

 

3、onreadystatechange 

        //onreadystatechange存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。

        //readyState  存有 XMLHttpRequest 的状态。从 0 到 4 发生变化

xhr.onreadystatechange = function ()

{

        if (xhr.readyState == 4 && xhr.status == 200) {

console.log(xhr.responseText);

            $("#p1").text(xhr.responseText);

        }

}

//onload 请求成功时触发的事件

    xhr.onload = function ()

    {

        //console.log(data.currentTarget.responseText);

        console.log(xhr.responseText);

        $("#p1").text(xhr.responseText);

    }

 

  1. 发送请求

    //send()将请求发送到服务器

xhr.send();

 

});

点击按钮会将p标签的内容更改成"/Jquery/changeTxt"这个路径的的内容。

//下面为控制器的代码

namespace JQuery.Controllers    //路径1.找到JQuery

{

    public class JqueryController : Controller

    {

public ActionResult changeTxt()    //路径2.找到JQuery后面加上changeTxt

        {

    //txt为我要修改的内容

            var txt = "应用ajax修改标签内容";

            return Json(txt,JsonRequestBehavior.AllowGet);

        }

    }

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值