首页 \ 问答 \ 使用ThreadLocal与Atomic(Using ThreadLocal vs Atomic)

使用ThreadLocal与Atomic(Using ThreadLocal vs Atomic)

根据ThreadLocal的javadoc,它听起来像是它针对1个原子字段的线程专用容器。

ThreadLocal的目的是表示单个Thread所有原子字段,还是仅当您有多个需要逻辑分组在一起的Atomic*实例时才提供便利容器?

我想我想知道为什么我会想要使用ThreadLocal而不是AtomicLongAtomicInteger ? 提前致谢!


According to ThreadLocal's javadoc, it sounds like its a thread-specific container for 1+ atomic fields.

Is the purpose of ThreadLocal to represent all the atomic fields for a single Thread, or is it to just provided a convenience container when you have multiple Atomic* instances that need to be logically grouped together?

I guess I'm wondering why I would ever want to use a ThreadLocal instead of, say, an AtomicLong or AtomicInteger? Thanks in advance!


原文:https://stackoverflow.com/questions/10357295
更新时间:2022-03-25 21:03

最满意答案

我必须通过作为第二个参数传递给validate方法的对象中的dom键( dom: $("#ajax_submit") )的值来指定我想要将事件耦合到的元素。

所以我需要的是以下内容:

$('#ajax_validated_form').validate('{% url validate_entity %}', {type: 'ul', dom: $("#ajax_submit"), event: "click"});

编辑:

还要知道#ajax_validated_form不一定要引用form元素来让验证工作,如果表单输入div中包含的内容,它也可以正常工作!

例如:

<div id="ajax_validated_form">
    {{ ajax_val_form }}
</div>

同样有效

<form id="ajax_validated_form" action="" method="post">
    {{ ajax_val_form }}
</form>

编辑2:

不要忘记在页面的脚本中包含以下内容(来自django文档 ):

    /// To enable Ajax calls with csrf_token protection ///////////////////
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    var csrftoken = getCookie('csrftoken');

    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    function sameOrigin(url) {
        // test that a given url is a same-origin URL
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
                // Send the token to same-origin, relative URLs only.
                // Send the token only if the method warrants CSRF protection
                // Using the CSRFToken value acquired earlier
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });
    /////////////////////////////////////////////////////////////////

I had to specify the element I wanted to couple the event to via the value of the dom key (dom: $("#ajax_submit")) in the object passed as second argument to the validate method.

So what I needed was the following:

$('#ajax_validated_form').validate('{% url validate_entity %}', {type: 'ul', dom: $("#ajax_submit"), event: "click"});

Edit:

Also know that the #ajax_validated_form doesn't necessarily have to refer to a form element to let the validation work, it works just as well if the form inputs where contained inside a div!

E.g.:

<div id="ajax_validated_form">
    {{ ajax_val_form }}
</div>

works just as well as

<form id="ajax_validated_form" action="" method="post">
    {{ ajax_val_form }}
</form>

Edit 2:

Don't forget to include the following (from the django docs) in the script of your page:

    /// To enable Ajax calls with csrf_token protection ///////////////////
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    var csrftoken = getCookie('csrftoken');

    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    function sameOrigin(url) {
        // test that a given url is a same-origin URL
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
                // Send the token to same-origin, relative URLs only.
                // Send the token only if the method warrants CSRF protection
                // Using the CSRFToken value acquired earlier
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });
    /////////////////////////////////////////////////////////////////

相关问答

更多
  • 您当前的代码不会将其他字段添加到表单中,只是将它们添加到表单外部的div#对话框中。 要将字段添加到表单,可以使用jquery的berfore()方法: $('#moreFields').before(result); 但是,由于你的addtoform.php根本不做任何计算,而简单的返回html,整个ajax请求是没有意义的。 你也可以用js添加字段: $('#moreFields').click (function(){ $(this).before('
  • 从提交按钮中删除onClick = "getdetails()"事件: 并修改$(".button").click(); Jquery处理程序如下: $(".button").click(function() { // validate and process form // first hide any error messa ...
  • 我得到了它的工作。 基本的技巧是,如果表单提交成功,我返回一个带有重定向状态代码和重定向到的URL的基本响应对象,而不是返回重定向。 然后我修改了我的displayForm()以查找它并重定向(如果找到它)。 这是Score()函数的修改代码: if form.is_valid(): form.save() messages.success(request, 'Score saved!') redirect = shortcuts.redirect('index') return http. ...
  • 我必须通过作为第二个参数传递给validate方法的对象中的dom键( dom: $("#ajax_submit") )的值来指定我想要将事件耦合到的元素。 所以我需要的是以下内容: $('#ajax_validated_form').validate('{% url validate_entity %}', {type: 'ul', dom: $("#ajax_submit"), event: "click"}); 编辑: 还要知道#ajax_validated_form不一定要引用form元素来让验证 ...
  • 你难道不能在ajax验证中添加no ajax部分,如下所示: $('form.ajax').on('submit',function(){ var that = $(this); url = that.attr('action'); method = that.attr('method'); data = {}; that.find('[name]').each(function(index,value){ var that = $(this), ...
  • 试试这个(按预期为我工作): HTML表单: