[] Front-end problem-solving learning stepped pit recording

 

Recently begun to learn to the front, white one, to be a step on the recording pit


20,191,021 Updated:

This site appears to use scroll-linked positioning effect. This may not work with asynchronous translation;

	<script>
		$(function(){
			 $(window).on("scroll",function(){
				var offset = $("html.body").scrollTop(); // 获取网页滚动偏移位
				if (offset>=100) {$("img").show(1000);}
				else {$("img").hide(1000);}
			});		
		});

	</script>

A simple scroll display or hide the js, run error in Firefox by listening to the page:

Photo Gallery and can not be achieved with the hidden effects.

 

solution:

	<script>
		$(function(){
			 $(window).on("scroll",function(){
				var offset = $(document).scrollTop(); // 获取网页滚动偏移位
				if (offset>=100) {$("img").show(1000);}
				else {$("img").hide(1000);}
			});		
		});

	</script>

While still show warning, but can be achieved snooping binding rolling animation. Possible reasons Firefox is positioning the wheel travel distance and other browsers different way.


20,191,029 Updated:

Forbidden (CSRF token missing or incorrect.): /xxx/xxx/

ajax data transmission at the rear end frame based django, if necessary to retain django comes CSRF verification needs to be added in the script js

        $.ajaxSetup({
            data:{
                csrfmiddlewaretoken:'{{ csrf_token }}'
            }
        })

If this method does not work you can also try this writing, provided that the page already exists in {% csrf_token%}:

               var csrfToken = $("[name='csrfmiddlewaretoken']").val();// 获取csrf_token
                $.ajax({
                    type: "POST",
                    url: "{% url 'space:change_profile' %}",
                    data: formData,
                    headers: {"X-CSRFToken": $.cookie('csrftoken')},
                    async: false,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function(response){
                        alert(reponse.toString());
                    },
                    error: function(e){
                        alert('Network Failure');
                    }

Is added CSRF_Token information headers in the manual.

Of course, all the html POST request section relates be added

{% csrf_token %}

For example, form part of a simple registration page:

            <form class="m-t" role="form" id="form" method="post" action="{% url 'main:register' %}" enctype="multipart/form-data">
                {% csrf_token %}
                <div class="form-group">
                    <label>学号</label>
                    <input type="text" name="uid" maxlength="20" placeholder="请输入您的学号" required id="id_uid" class="form-control">
                </div>
                <div class="form-group">
                    <label>用户名</label>
                    <input type="text" name="username" maxlength="20" placeholder="请设置您的用户名" required id="id_username" class="form-control">
                </div>
                <div class="form-group">
                    <label>密码</label>
                    <input type="password" name="password" maxlength="16" placeholder="请输入密码" required id="id_password" class="form-control">
                </div>
                <div class="form-group">
                    <label>再次输入密码</label>
                    <input type="password" name="password_rep" maxlength="20" placeholder="请再次输入密码" required id="id_password_rep" class="form-control">
                </div>
                <div class="form-group">
                    <label>名字</label>
                    <input type="text" name="first_name" maxlength="30" placeholder="请留下您的名字" id="id_first_name" class="form-control">
                </div>
                <div class="form-group">
                    <label>姓氏</label>
                    <input type="text" name="last_name" maxlength="30" placeholder="请留下您的姓氏" id="id_last_name" class="form-control">
                </div>
                <div class="form-group">
                    <label>头像</label>
                    <input type="file" name="profile" placeholder="点击选择您的头像" id="id_profile" class="form-control" onchange="verificationPicFile(this)">
                </div>
                <div>
                    <label>电子邮件地址</label>
                    <div class="row">
                        <div class="form-group col-md-8">
                            <input type="email" name="email" maxlength="40" placeholder="请设置您的验证邮箱" id="id_email" class="form-control">
                        </div>
                        <div class="form-group col-md-2 offset-1">
                            <button type="button" class="ladda-button btn btn-primary" id="send-email-button" data-style="zoom-in">Send</button>
                        </div>
                    </div>
                </div>
                <div>
                    <label>验证码</label>
                    <input type="text" name="code" maxlength="4" placeholder="请输入验证码" id="id_code" class="form-control">
                </div>
                <div class="form-group">
                    <div class="checkbox i-checks"><label> <input type="checkbox"><i></i> Agree the terms and policy </label></div>
                </div>
                <button type="submit" class="btn btn-primary block full-width m-b">Register</button>

20,191,029 Updated:

Django ajax receiving picture data transmission

JS part:

                var csrfToken = $("[name='csrfmiddlewaretoken']").val();// 获取csrf_token
                $.ajax({
                    type: "POST",
                    url: "{% url 'space:change_profile' %}",
                    data: formData,
                    headers: {"X-CSRFToken": $.cookie('csrftoken')},
                    async: false,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function(response){
                        alert(reponse.toString());
                    },
                    error: function(e){
                        alert('Network Failure');
                    }
                });

View function:

def change_profile(request):                                                                                             # 获取头像
    if request.method == "POST":
        profile = request.POST.get("profile")                                                                           # 获取用户设置的验证邮箱
        print("PROFILE的内容为",profile)
        return ajax_response("0", "Successfully reponsed", {"profile_token": 1})
    else:
        raise InvalidOperation("无效的请求")

Found the back end still can not get to ajax transferred to the picture, in fact, can not get out before another question is:

urlpatterns = [
	url(r"^(?P<username>\w+)/$",views.center,name="center"),															# 用户中心页面
	url(r"^change_profile/",views.change_profile,name="change_profile"),												# 修改头像
]

When I configure URL so if I change the picture spread with ajax change_profile () function view, it will match the first name for the URL center in, because there is no precise match.

To modify the URL change_profile

urlpatterns = [
	url(r"^(?P<username>\w+)/$",views.center,name="center"),															# 用户中心页面
	url(r"^user/change_profile/",views.change_profile,name="change_profile"),												# 修改头像
]

After the discovery of view function to get the picture always None, because the images are not stored in request.POST object, but request.FILES in:

def change_profile(request):                                                                                             # 获取头像
    if request.method == "POST":
        profile = request.FILES.get("profile")                                                                           # 获取用户设置的验证邮箱
        print("PROFILE的内容为",profile)
        return ajax_response("0", "Successfully reponsed", {"profile_token": 1})
    else:
        raise InvalidOperation("无效的请求")

20,191,030 update

JS refresh picture element

After the user to re-upload pictures updated avatars, images on the page still does not change. User picture changed after refresh the page. We certainly do not want the entire page to reload, but only want to reload the corresponding img tag.

I tried to find some way found no particular partial refresh pictures fly method, a feasible way is to add a random value (such as date) after the value of the src attribute of the img tag, you can achieve the user to upload image files , modify the back-end server image files, the front page immediately update to the new image.

                var csrfToken = $("[name='csrfmiddlewaretoken']").val();// 获取csrf_token
                $.ajax({
                    type: "POST",
                    url: "{% url 'space:change_profile' username %}",
                    data: formData,
                    headers: {"X-CSRFToken": $.cookie('csrftoken')}, // 这里的值可以用csrfToken替代!否则需要预先导入jquery.cookie.js
                    async: false,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function(response){// 成功修改则即刻更新图片
                        console.log("劳资来更新头像了。。。");
                        var profileSrc = $("img#showImg").attr("src");
                        var date = new Date()
                        $("img#showImg").attr("src",profileSrc+"?"+date.getTime());
                    },
                    error: function(e){
                        alert('Network Failure');
                    }
                });

20,191,101 update

$ .Ajax () problem can not be assigned to a global variable

        $("button.m-b").click(function(){
            var csrfToken = $("[name='csrfmiddlewaretoken']").val();
            var username = $("input[name='username']").val();
            var password = $("input[name='password']").val();
            var flag = false // 控制事件冒泡
            $.ajax({
                type: "POST",
                url: {% url 'main:validate_login_formdata' %},
                data: {'username': username, 'password': password},
                headers: {"X-CSRFToken": csrfToken},
                success: function(response){// 成功修改则即刻更新图片
                    response = JSON.parse(response);
                    if(response.code=='0') {
                        alert(response.msg);
                    }
                    else {
                        console.log("我也曾来过这里")
                        flag = true;}
                },
                error: function(e){
                    alert('Network Failure');
                }
            });
            console.log(flag)
            return flag;

Some control ajax submit button clicks, and hope does not happen when a user name and password does not match the bubble (ie return flag = false), but want to modify the flag in the success of the match so that returns a value of true event bubbling (page Jump). But the actual operation flag is always false, the page does not always jump.

The reason is loaded synchronously, when the $ .ajax () in async attribute parameter is not set, the default will be running to return flag, and then is the content () of $ .ajax, if required synchronous operation, you need to set async: false, ie can:

        $("button.m-b").click(function(){
            var csrfToken = $("[name='csrfmiddlewaretoken']").val();
            var username = $("input[name='username']").val();
            var password = $("input[name='password']").val();
            var flag = false // 控制事件冒泡
            $.ajax({
                type: "POST",
                url: {% url 'main:validate_login_formdata' %},
                data: {'username': username, 'password': password},
                headers: {"X-CSRFToken": csrfToken},
                async: false,
                success: function(response){// 成功修改则即刻更新图片
                    response = JSON.parse(response);
                    if(response.code=='0') {
                        alert(response.msg);
                    }
                    else {
                        console.log("我也曾来过这里")
                        flag = true;}
                },
                error: function(e){
                    alert('Network Failure');
                }
            });
            console.log(flag)
            return flag;

20,191,108 update

context.drawImage canvas of the canvas tag () function does not display the picture of the problem:

Recently https://www.w3school.com.cn/tags/canvas_drawimage.asp learn entry-level label use on canvas, met drawImage function (try it yourself https://www.w3school.com.cn/tiy /t.asp?f=html5_canvas_drawimage ), looking at the example it gave me a whole long time could not figure out what to do this function, I thought it was something you can use the mouse to draw on the whiteboard.

And finally figure out the picture did not show up so a white board because of the pictures on the ctx.drawImage loaded onto the page has not finished loading the JS, so the canvas is white. The solution is to use windows.onload trap ctx.drawImage to:

Adapted from https://www.w3school.com.cn/tiy/t.asp?f=html5_canvas_drawimage :

<!DOCTYPE html>
<html>
<body>

<p>要使用的图像:</p>
<img id="tulip" src="/i/eg_tulip.jpg" alt="The Tulip" />

<p>画布:</p>
<canvas id="myCanvas" width="500" height="300" style="border:1px solid #d3d3d3;background:#ffffff;">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("tulip");
window.onload = function(){
  ctx.drawImage(img,10,10);
}
</script>

</body>
</html>

 

 

Published 40 original articles · won praise 133 · views 440 000 +

Guess you like

Origin blog.csdn.net/CY19980216/article/details/102671478