从ajax发送post请求到python函数但是接收GET请求?

时间:2015-05-14 06:33:40

标签: ajax django post get

我是Django的新手。我正在向python函数发送一个ajax POST请求,而python函数又将数据存储在ajax的变量中并返回HttpResponse。所以我在python中检查了request.method它的GET。

$('.btn-unfollow').hide();
$('.btn').hover(function () {
    $('.btn').toggle();
});

这是我的ajax请求。

将数据发送到此功能。

$.ajax({
  url:"create_post/",
  type:"POST",

  data : {F_Name: First_Name ,L_Name: Last_name,Eadd: Email , Password: Pass},
  success:function(){
    window.location.href="create_post/";
    console.log ("Success")
  },
  cache:false,
  failure: function(errMsg) {
    alert(errMsg);
  }
});

当我选中def create_post(request): if request.method == 'GET': First_name=request.GET['F_Name']; Last_Name=request.GET["L_Name"]; Email_address=request.GET["Eadd"]; Pass=request.GET["Password"]; return HttpResponse("<html><body>hi this is me .</body></html>"); 给我return(request.method)时。

有人可以解释这种行为吗? 在这个场景中我有GET的功能,DJango给了我内部服务器500错误。

由于

2 个答案:

答案 0 :(得分:2)

我很惊讶地发现你们没有人注意到他有定义方法:&#34; POST&#34;在他的ajax和他的功能用于&#34; GET&#34;请求。

他获得打印请求输出的主要原因是.method =&#34; GET&#34;和500错误是因为使用window.location.href =&#34; create_post /&#34;在他的ajax成功功能。默认情况下,每个请求都是一个get请求,除非我们明确定义它&#34; POST&#34;或任何其他。

所以这就是这样的, - Ajax通过POST调用url,由于未知原因,响应来自成功函数(根据发布的POST方法看起来奇怪的因为ajax请求没有返回任何内容)。 - 成功函数再次通过GET请求调用相同的URL(页面刷新),并且他看到print request.method为&#34; GET&#34; 500错误因为这是错误的方法。

答案 1 :(得分:-1)

你的ajax方法是post,所以我认为你的views.py可能会试试这个

def create_post(request):
    if request.method == 'POST':
        First_name=request.POST['F_Name']
        Last_Name=request.POST["L_Name"]
        Email_address=request.POST["Eadd"]
        Pass=request.POST["Password"]
    return HttpResponse("<html><body>hi this is me .</body></html>")