分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

js和jQuery实现的Ajax

发布时间:2023-09-06 02:23责任编辑:董明明关键词:jsjQueryAjax

1. JS实现Ajax

<!doctype html><html lang="en"><head> ??<meta charset="UTF-8"> ??<meta name="viewport" ????????content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> ??<meta http-equiv="X-UA-Compatible" content="ie=edge"> ??<title>Document</title></head><body> ??<button type="submit" id="js_ajax_test">Ajax测试</button> ??<script> ??????var js_ajax_test = document.getElementById("js_ajax_test"); ??????js_ajax_test = function () { ??????????var xmlHttp = new XMLHttpRequest(); ??????????xmlHttp.open("POST", "/js_ajax_test/", true); ??????????xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); ??????????xmlHttp.send("username=yang&password=123"); ??????????xmlHttp.onreadystatechange = function () { ??????????????if (xmlHttp.readyState === 4 && xmlHttp.status ===200){ ??????????????????alert(xmlHttp.responseText) ??????????????} ??????????} ??????} ??</script></body></html>

2. jQuery实现的Ajax

最基本的jQuery发送Ajax请求示例:

<!doctype html><html lang=""><head> ??<meta charset="UTF-8"> ??<meta name="viewport" ????????content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> ??<meta http-equiv="X-UA-Compatible" content="ie=edge"> ??<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> ??<title>ajax test</title></head><body> ??<button id="ajaxTest">AJAX测试</button> ??<script> ??????$("#ajaxTest").click(function () { ??????????$.ajax({ ??????????????url: "/ajaxTest/", ??????????????type: "POST", ??????????????data: {username: "yang", password:123}, ??????????????success: function (data) { ??????????????????alert(data) ??????????????} ??????????}) ??????}) ??</script></body></html>

views.py

def ajax_test(request): ??return render(request, "ajax_test.html")def ajaxTest(request): ??username = request.POST.get("username") ??password = request.POST.get("password") ??return HttpResponse("用户名:{} 密码:{}".format(username, password))

urls.py

from django.conf.urls import urlfrom django.contrib import adminfrom app01 import viewsurlpatterns = [ ??url(r‘^admin/‘, admin.site.urls), ??url(r‘^ajax_test/‘, views.ajax_test), ??url(r‘^ajaxTest/‘, views.ajaxTest)]

3. Ajax中使用JSON

data参数中的键值对,如果值不为字符串,需要将其转换成字符串类型。

如果没有转换为字符串,那么views中的代码就接收不到password的值。

<script> ??????$("#ajaxTest").click(function () { ??????????$.ajax({ ??????????????url: "/ajaxTest/", ??????????????type: "POST", ??????????????data: {username: "yang", password:JSON.stringify([1, 2, 3])}, ??????????????success: function (data) { ??????????????????alert(data) ??????????????} ??????????}) ??????})</script>

js和jQuery实现的Ajax

原文地址:https://www.cnblogs.com/yang-wei/p/10009053.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved