《jQuery 发送 Ajax 请求》

《jQuery 发送 Ajax 请求》

1. 发送 POST JSON 请求

let reqBody = { captcha_challenge_field: document.getElementById("captcha_challenge_field_id").value, manual_captcha_challenge_field: document.getElementById("your_manual_captcha_challenge_field_id").value }; $.ajax({ url: "/your-service/captcha_challenge/verify", // 必需是大写的 POST !!!! type: "POST", headers: { "Content-Type": "application/json" }, data: JSON.stringify(reqBody), success: function (result) { // 注意:服务器返回的布尔值在客户端接收时会变成字符串 if ("false" == result) { // 验证失败,提示用户重新输入验证码 $("#tell_user_input_is_incorrect").css("display", "block"); $("#captcha-challenge-embed-form").css("display", "none"); // 刷新验证码图片 window.yourCaptchaEmbed.fetchSessionstr(); // 2 秒后,错误信息消失,验证码框重新出现 setTimeout(function () { $("#tell_user_input_is_incorrect").css("display", "none"); $("#captcha-challenge-embed-form").css("display", "block"); }, 2000); } else { // 验证成功,删除验证码浮层 $("#captcha-div").remove(); } } });

2. 发送 form 表单数据(application/x-www-form-urlencoded)

let reqBody = [ 'challenge=', document.getElementById('captcha_challenge_id').value, '&', 'response=', document.getElementById('captcha_response_id').value, '&', 'remoteip=', clientIp, '&', 'bypass_mode=', 'true', '&', 'zone=', getZone() ].join(''); $.ajax({ url: 'http://YOUR_SERVER:8515/verify', // 必需是大写的 POST !!!! type: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, data: reqBody, success: function (data) { let result = JSON.parse(data); // 验证成功,则跳转到之前的页面 if (result.success === true) { window.location.reload(); } else { // 验证失败,刷新验证码图片 window.Captcha.fetchSessionstr(); } } });

3. 注意:type 必须大写

使用 ajax 发送 POST 请求时,type 必须写为大写 POST;写成小写 post 可能不被正确识别。

4. 官方文档

  • https://api.jquery.com/jQuery.ajax/
阅读 — · 全站 —
🎸 我的歌单 0 首