简体   繁体   中英

Django POST With Using Ajax

I have one app name register_login and this app manages login and register opeartions. I have a form on localhost:8000/login page and i want that the button redirects to my func in register_login app but i cant do it. I'm new at Django Framework. How can i handle this?

MAIN URLS.PY

from django.conf.urls import include,url
from django.contrib import admin
from register_login.views import login, register, test


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^homepage/', include('homepage.urls')),
    url(r'^login/$', login),
    url(r'^register/$', register),
    url(r'^success/$', test),
]

LOGIN PAGE .HTML

<form id=registerLogin style="margin-top: 30px; margin-left: 350px;">
      <header>Login</header>
      <label >Username <span>*</span></label>
      <input id="username"/>
      <label >Password <span>*</span></label>
      <input id="password"/>
      <button id="login">Login</button>
      <h1 style="margin-left: 20px;">Are you not registered?</h1>
      <button id="register">Register</button>
</form>

At the end of this html there is my .js file. I didnt forget.

JAVASCRIPT

if (!jQuery) { throw new Error("This page requires jQuery") }


function readInput() {
    e.preventDefault();
    var userName = document.getElementById('username').value;
    var password = document.getElementById('password').value;
    debugger

    $.ajax({
        type: "POST",
        url: "/success/",
        data: {'username':username,'password':password, csrfmiddlewaretoken: '{{ csrf_token }}'},
        dataType: 'json',
        success : function(json) {
            $('#post-text').val(''); // remove the value from the input
            console.log(json); // log the returned json to the console
            console.log("success"); // another sanity check
        },     
    }); 
}

(function ($) {

$("#login").click(function(){
    readInput();
});


})(jQuery);

And finally my function. Its in register_login app as i said before

REGISTER_LOGIN VIEW

def test(request):
    embed()
    if request.method == 'POST':
        embed()
    return HttpResponse("hell world")

I tried to change url like "/register_login/success/","/register_login/success","/register_login/success/$","/success/","success/" or "/success/$". Nothing works

I need to go that function but it doesnt :(

Since you are logging in via ajax, you can not redirect in your test view. What you can do is add a redirect in your ajax success function. Something like this:

// similar behavior as an HTTP redirect
window.location.replace("/some-url/");

or

// similar behavior as clicking on a link
window.location.href = "/some-url/";

Also, you need to fix your javascript code, add preventDefault in the click handler and remove it in the readInput. You also need to remove the quotes in the data object and make sure you used the correct variables. Something like this:

$(function() {
    function readInput() {
        var username = document.getElementById('username').value;
        var password = document.getElementById('password').value;

        $.ajax({
            type: "POST",
            url: "/success/",
            data: {
                username: username,
                password: password,
                csrfmiddlewaretoken: '{{ csrf_token }}'
            },
            dataType: 'json',
            success : function(json) {
                window.location.replace("/some-url/");
            }
        }); 
    }

    $("#login").click(function(e){
        e.preventDefault();
        readInput();
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM