jQuery的ajax与django传参

本文介绍了如何使用Django框架处理GET和POST请求,并通过jQuery实现AJAX与服务器的交互。提供了三种GET请求及两种POST请求的具体实现方式。

Get方式传参

Django中的代码如下:

  • urls.py代码:
from django.conf.urls import url
from django.contrib import admin
import AjaxTest.views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r"^index/$",AjaxTest.views.index),
]
  • views.py代码:
from django.http import HttpResponse

def index(req):
    print req.GET.get('url')
    if req.GET.get('url')=='test':
        return HttpResponse("hello,this is a test")
    else:
        return HttpResponse("hahahaha")

jQuery中的代码如下:

  • 方式1:
$("input").click(function() {
	$.get("/index/?url=test", function (response, status, xhr) {
		$(".box").html(response);
	});
});
  • 方式2:
$("input").click(function() {
    $.get("/index/", "url=test", function (response, status, xhr) {
        $(".box").html(response);
    });
});
  • 方式3:

 

$("input").click(function() {
	$.get("/index/",{
		url:"test"
	},function(response,status,xhr){
		$(".box").html(response);
	});
});

POST方式传参

Django中的代码如下:

  • urls.py代码:
from django.conf.urls import url
from django.contrib import admin
import AjaxTest.views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r"^index/$",AjaxTest.views.index),
]
  •  views.py代码如下:
def index(req):
    if req.POST.get('url')=='test':
        return HttpResponse("htllo,this is a test")
    else:
        return HttpResponse("hahahahah")

jQuery中的代码如下:

  • 方式1:
$("input").click(function () {
	$.post("/index/","url=test",function(response,status,xhr){
		$(".box").html(response)
	});
});
  • 方式2:
$("input").click(function(){
	$.post("/index/",{
		url:"test"
	},function (response,status,xhr) {
		alert(status);
		$(".box").html(response)
	});
});
  • 方式3:
   $("input").click(function(){
        $.ajax({
            type:"POST",
            url:"/index/",
            data:{url:"test"},
            success:function (response,status,xhr) {
                $(".box").html(response);
            }
        })
    });

  

转载于:https://www.cnblogs.com/Yellow0-0River/p/5499885.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值