js原生ajax请求
创始人
2025-01-07 07:36:13
0

以下是使用 JavaScript 原生的 XMLHttpRequest 对象进行 ajax 请求的示例代码:

function ajaxRequest(method, url, data, callback) {   var xhr = new XMLHttpRequest();    xhr.open(method, url, true);    if (method === 'POST') {     xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');   }    xhr.onreadystatechange = function() {     if (xhr.readyState === 4 && xhr.status === 200) {       callback(xhr.responseText);     }   };    if (method === 'POST') {     xhr.send(data);   } else {     xhr.send();   } }  // 使用示例 ajaxRequest('GET', 'https://example.com/data', null, function(response) {   console.log(response); });  ajaxRequest('POST', 'https://example.com/submit', 'key1=value1&key2=value2', function(response) {   console.log(response); }); 

在上述代码中:

  • ajaxRequest 函数接受请求方法(method)、请求
    URL(url)、要发送的数据(data)和回调函数(callback)作为参数。
  • 通过 open 方法设置请求的方法和 URL,并指定是否异步。 根据请求方法设置相应的请求头。
  • 通过 onreadystatechange 事件监听请求状态的变化,当请求完成且状态码为 200 时,调用回调函数处理响应数据。
  • 最后根据请求方法发送数据。

例如,在上面的使用示例中,分别进行了 GET 和 POST 请求,并在回调函数中打印响应的文本内容。

相关内容

热门资讯

透视app(WPK)原来存在有... 透视app(WPK)原来存在有挂(透视)wpk刷入池率脚本(线上教程)1、玩家可以在wpk刷入池率脚...
透视计算!hhpoker透视工... 透视计算!hhpoker透视工具,德州透视插件,专业教程(有挂解密);1、hhpoker透视工具系统...
透视透视挂!wepoker黑侠... 透视透视挂!wepoker黑侠辅助器正版下载,wepoker插件功能辅助器(确实存在有挂)1、金币登...
透视最新!aapoker怎么设... 透视最新!aapoker怎么设置提高好牌几率(透视)破解侠是真的(一贯真的是有挂)1、每一步都需要思...
透视规律(WPK)其实真的是有... 透视规律(WPK)其实真的是有挂(透视)wpk显示有作弊(技巧教程)亲,关键说明,wpk显示有作弊赛...
透视插件!德州透视插件,hhp... 透视插件!德州透视插件,hhpoker德州透视,力荐教程(有挂辅助);1、hhpoker德州透视系统...
透视挂!wepoker亲友圈有... 透视挂!wepoker亲友圈有用吗,wepoker有辅助吗(果然真的有挂)1、下载好wepoker亲...
透视代打!aapoker透视怎... 透视代打!aapoker透视怎么用(透视)能控制牌(果然真的是有挂)1、aapoker透视怎么用系统...
透视美元局(WPK)确实真的有... 透视美元局(WPK)确实真的有挂(透视)wpk透视是真的吗(透牌教程)1、wpk透视是真的吗系统规律...
透视真的!hhpoker作弊码... 透视真的!hhpoker作弊码,hhpoker免费透视脚本,介绍教程(有挂插件);1、上手简单,内置...