URL
URL在前端开发中经常被使用,它可以获得页面URL地址中的各种参数值,用于后续操作。比如,我们可以获取当前页面的URL地址:
let url = window.location.href;console.log(url); // https://example/index.html
除此之外,我们还可以获取URL地址中的各种参数值:
假设我们的URL地址是这样的:https://example/?name=张三&age=18
我们可以如下获取URL参数:
// 获取单个参数值let name = window.location.search.match(/name=([^&]*)/)[1];console.log(name); // 张三// 获取多个参数值,返回一个对象function getUrlParams() {let match,reg = /([^&=]+)=([^&]*)/g,params = {};while ((match = reg.exec(window.location.search))) {params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);}return params;}console.log(getUrlParams()); // {name: "张三", age: "18"}另外,我们还可以修改页面的URL地址,比如利用pushState和replaceState方法来实现无刷新页面跳转:
let stateObj = { title: "page2", url: "example/page2" };history.pushState(stateObj, "page2", "example/page2"); // 当前URL变为:example/page2history.replaceState(stateObj, "page2", "example/page2"); // 替换当前URL为:example/page2ctx
ctx通常指的是上下文,是指前后端交互时使用的上下文对象。在Angular、Vue等前端框架中,ctx也常常被使用,它保存了当前请求的一些基本信息,如当前请求的URL、请求头信息等。
在JavaScript中,我们可以通过JavaScript中的AJAX请求向后端请求数据,并且将后端返回的数据放入ctx中:
// 前端AJAX请求let xhr = new XMLHttpRequest();xhr.open("POST", "/api/order/save", true);xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8");xhr.onreadystatechange = function () {if (xhr.readyState == 4 && xhr.status == 200) {let res = JSON.parse(xhr.responseText);console.log(res);// 将结果放入ctx中let ctx = {};ctx.data = res.data;ctx.msg = res.message;}};xhr.send(JSON.stringify(requestData));通过ctx,我们可以在前端拿到后端返回的数据,并进行相应的操作。此外,ctx还可以用于保存当前用户的登录信息、路由信息等。
总结
URL和ctx在JavaScript中是非常常用的概念,我们可以通过URL获取当前页面的地址和参数值,也可以通过ctx保存一些基本信息,在前端开发中具有重要的作用。希望本文对大家有所帮助。
上一篇:css按钮上文字居中
下一篇:javascript中优先级









