javascript - 모바일 양식 제출 페이지, 네트워크가 느린 경우 양식이 두 번 제출됩니다.

WBOY
풀어 주다: 2016-10-22 00:14:24
원래의
1289명이 탐색했습니다.

네트워크 상태가 좋을 때는 모바일 웹사이트 제출 페이지가 정상적으로 작동합니다. 하지만 Fiddler는 동일한 콘텐츠를 캡처하여 두 번 제출합니다.

답글 내용:

네트워크 상태가 좋을 때는 모바일 웹사이트 제출 페이지가 정상적으로 작동합니다. 하지만 Fiddler는 동일한 콘텐츠를 캡처하여 두 번 제출합니다.

제 접근 방식은 서버 측에서 토큰을 생성하고 제출할 때 토큰을 확인하는 것입니다. 두 번째 확인은 양식이 제출될 때 제출 버튼을 비활성화하는 것입니다.

<code>// 提交表单数据到后台处理
$.ajax({
    type: "post",
    data: studentInfo,
    contentType: "application/json",
    url: "/Home/Submit",
    beforeSend: function () {
        // 禁用按钮防止重复提交
        $("#submit").attr({ disabled: "disabled" });
    },
    success: function (data) {
        if (data == "Success") {
            //清空输入框
            clearBox();
        }
    },
    complete: function () {
        $("#submit").removeAttr("disabled");
    },
    error: function (data) {
        console.info("error: " + data.responseText);
    }
});</code>
로그인 후 복사
Csrf 검증 수업

<code><?php

// +----------------------------------------------------------------------
// | CSRF安全验证类 @pushaowei
// +----------------------------------------------------------------------
// | [Usage]
// |    // 后端
// |    use library\Base\NoCSRF;
// |    session_start();   
// |    if ($this->getRequest()->isPost()) {
// |            
// |        try {
// |            ##验证TOKEN  
// |            NoCSRF::check( 'csrf_token', $_POST, true, 60*10, false ); //60*10为10分钟(null为不验证时间)
// |            $result = 'CSRF check passed. Form parsed.';
// |            //$this->getRequest()->getPost('field');
// |            echo $result;       
// |        } catch ( Exception $e ) {
// |            echo $e->getMessage() . ' Form ignored.'; 
// |        }      
// |    } else {   
// |        #生成TOKEN  
// |        $token = NoCSRF::generate( 'csrf_token' );
// |        $this->getView()->assign('token', $token);
// |        $this->getView()->display('页面');
// |    }
// |    // 前端
// |    <input type="hidden" name="csrf_token" value="{$token}">
// +----------------------------------------------------------------------

class NoCSRF
{
    protected static $doOriginCheck = false;
    /**
     * Check CSRF tokens match between session and $origin. 
     * Make sure you generated a token in the form before checking it.
     *
     * @param String $key The session and $origin key where to find the token.
     * @param Mixed $origin The object/associative array to retreive the token data from (usually $_POST).
     * @param Boolean $throwException (Facultative) TRUE to throw exception on check fail, FALSE or default to return false.
     * @param Integer $timespan (Facultative) Makes the token expire after $timespan seconds. (null = never)
     * @param Boolean $multiple (Facultative) Makes the token reusable and not one-time. (Useful for ajax-heavy requests).
     * 
     * @return Boolean Returns FALSE if a CSRF attack is detected, TRUE otherwise.
     */
    public static function check( $key, $origin, $throwException=false, $timespan=null, $multiple=false )
    {
        $session = Session::getInstance();

        if ( !$session->has( 'csrf_' . $key ) )
            if($throwException)
                throw new \Exception( 'Missing CSRF session token.' );
            else
                return false;
            
        if ( !isset( $origin[ $key ] ) )
            if($throwException)
                throw new \Exception( 'Missing CSRF form token.' );
            else
                return false;

        // Get valid token from session
        $hash = $session->get('csrf_' . $key);
        
        // Free up session token for one-time CSRF token usage.
        if(!$multiple)
            $session->forget('csrf_' . $key);

        // Origin checks
        if( self::$doOriginCheck && sha1( $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'] ) != substr( base64_decode( $hash ), 10, 40 ) )
        {
            if($throwException)
                throw new \Exception( 'Form origin does not match token origin.' );
            else
                return false;
        }
        
        // Check if session token matches form token
        if ( $origin[ $key ] != $hash )
            if($throwException)
                throw new \Exception( 'Invalid CSRF token.' );
            else
                return false;

        // Check for token expiration
        if ( $timespan != null && is_int( $timespan ) && intval( substr( base64_decode( $hash ), 0, 10 ) ) + $timespan < time() )
            if($throwException)
                throw new \Exception( 'CSRF token has expired.' );
            else
                return false;

        return true;
    }

    /**
     * Adds extra useragent and remote_addr checks to CSRF protections.
     */
    public static function enableOriginCheck()
    {
        self::$doOriginCheck = true;
    }

    /**
     * CSRF token generation method. After generating the token, put it inside a hidden form field named $key.
     *
     * @param String $key The session key where the token will be stored. (Will also be the name of the hidden field name)
     * @return String The generated, base64 encoded token.
     */
    public static function generate( $key )
    {
        $session = Session::getInstance();

        $extra = self::$doOriginCheck ? sha1( $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'] ) : '';
        // token generation (basically base64_encode any random complex string, time() is used for token expiration) 
        $token = base64_encode( time() . $extra . self::randomString( 32 ) );
        // store the one-time token in session
        $session->put('csrf_' . $key, $token);

        return $token;
    }

    /**
     * Generates a random string of given $length.
     *
     * @param Integer $length The string length.
     * @return String The randomly generated string.
     */
    protected static function randomString( $length )
    {
        $seed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijqlmnopqrtsuvwxyz0123456789';
        $max = strlen( $seed ) - 1;

        $string = '';
        for ( $i = 0; $i < $length; ++$i )
            $string .= $seed{intval( mt_rand( 0.0, $max ) )};

        return $string;
    }

}
?></code>
로그인 후 복사

한 번 클릭하고 한 번 제출해야 합니다. 네트워크 속도가 느려서 한 번 클릭하고 두 번 제출하는 것은 불가능합니다. 이벤트가 어떻게 뿌리 없는 물과 같을 수 있습니까? 그렇다면 코드에 문제가 있는 것 같습니다

그렇게 복잡할 필요는 없습니다.

두 요청을 보세요

. 첫 번째 요청이 다운되었는지 확인하세요. header(클릭으로 인해 발생한 경우 클릭 후 dom 요소의 클릭 이벤트를 비활성화함)인지 확인하세요. 两次点击으로 인해 발생했습니다. 代码部分原因

그런데

님과 请求的代码님이 캡처한 데이터를 보내주세요. Fiddler

두 번 제출하는 이유는 대략 두 가지입니다.

첫째, 클릭 이벤트가 두 번 발생합니다(이 경우는 네트워크 속도에 의존하지 않습니다)
이는 대부분 일부 js 플러그인으로 인해 발생합니다. Google이 필요합니다.
이벤트가 두 번 실행되는 경우가 더 많습니다. iscroll.js 둘째, 네트워크 속도가 빨라서 사용자가 클릭을 할 수 없습니다.

앞에 여러 번 있어야 합니다. ajax 버튼을 제거하세요. 양식을 여러 번 제출할 수 있는 경우 disabled 뒤의 ajax을 제거하세요. disabled

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!