繁体   English   中英

jQuery:在注释div中循环并获取字段值

[英]jQuery: loop through comment div and get fields values

我试图通过ajax提交用户评论,所以试图遍历<div class="comments-fields">以获取我需要的2个字段的值。

到目前为止,我得到的只是这个错误,好像我没有填写我的注释文本区域。

SQLSTATE [23000]:违反完整性约束:1048列'comment'不能为空(SQL:插入commentsuser_idcommentparent_idparentsupdated_atcreated_at )的值(1 updated_at created_at 00 :57:59,2015-10-17 00:57:59))

console.log(formData)给出了类似的信息。

formData {}
__proto__: FormData
append: append()
constructor: FormData()
__proto__: Object

我该如何实现? 如果有更好的方法,请提出建议。

HTML

 <div class="comment-fields">
     <div class="commenter-comment">
        <div class="form-group col-md-12">
            <textarea id="commenter_comment" name="commenter_comment" class="form-control comment-field" title="User's comment" placeholder="Comment Text"></textarea>

         </div>
     </div>

     <div class="commenter-name-email">
         <input type="hidden" id="commenter_parent" name="commenter_parent" class="commenter-parent" value="0">
      </div>

      <div class="commenter-captcha">
          <div class="col-md-3 text-right">
              <a href="javascript:void(0)" class="btn btn-info post-this-comment">Comment</a>
           </div>
       </div>

 </div>

Javascript

function commenter_fields(){
    return [
        'commenter_parent',
        'commenter_user_id',
        'commenter_comment'
    ];
}

$(document).on('click', 'a.post-this-comment', function(){
    var formData = new FormData();
    var arrayelem = commenter_fields();
    var elem;
    for(var i=0, size = arrayelem.length; i<size; i++){
        elem = arrayelem[i];
        formData.append(elem, $('#'+elem).val());
    }
    formData.append('per_page', $('.comments_per_page').val());
    var request = $.ajax({ // push question data to server
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : 'post_this_comment', // the url where we want to POST
        data        : formData, // our data object
        dataType    : 'json',
        processData : false,
        contentType : false
    });
    request.done(comment_done_handler);
    request.fail(comment_fail_handler); // fail promise callback
});

我正在使用PhpStrom,单击FormData()会导致此文件

C:\\ Program Files(x86)\\ JetBrains \\ PhpStorm 9.0 \\ plugins \\ JavaScriptLanguage \\ lib \\ JavaScriptLanguage.jar!\\ com \\ intellij \\ lang \\ javascript \\ index \\ predefined \\ HTML5.js

这是FormData

FormData.prototype.append = function(name,value) {};
FormData = {};

我建议使用常规对象,因为它们比formData更容易使用(我认为)。

jQuery文档在ajax帖子中为数据设置指定了Type: PlainObject or String or Array ,这让我认为它们也喜欢对象。

因此,您的点击处理程序可以执行以下操作:

var form_data = {
    'per_page': $('.comments_per_page').val()
};

var arr = [
    'commenter_parent',
    'commenter_user_id',
    'commenter_comment'
];

for (var i in arr; i < arr.length; i++) {
    var elem = arr[i];
    form_data[elem] = $('#' + elem).val();
}

// console.log(form_data); // something like => Object {per_page: "some_value", commenter_parent: "some_value", commenter_user_id: "some_value", commenter_comment: "some_value"}

var request = $.ajax({
    type: 'POST',
    url: 'your_url_here',
    data: form_data,
    dataType: 'json'
});

request.done(comment_done_handler);
request.fail(comment_fail_handler);

一种更简单的方法是在元素上使用数据属性,并仅从像这样的值构建数据字符串:

 $(document).on('click', 'a.post-this-comment', function () { var dataArray=[]; // array to temporarilly store our data $('#comment-fields').find('.commenter-field').each(function(i,e){ //loop through all of the fields we need values from, I gave them all the class `commenter-field` var $element =$(e); // cache the element var type=$element.data('comment-field-type'); // get the name of the data, stored as a data attribute var value=encodeURIComponent($element.val()); // get the value, you MUST encode the value, otherwise, you WILL run into issues at some point with illegal chars dataArray.push(type+'='+value); // combine the type and value separated by `=` }); var dataString=dataArray.join('&'); // join the array with `&` between each name/value pair var request = $.ajax({ // push question data to server type: 'POST', // define the type of HTTP verb we want to use (POST for our form) url: 'post_this_comment.php', // the url where we want to POST, missing file extension here? data: dataString, // our data string dataType: 'json', // only if your code expects a json response from `post_this_comment.php` }); request.done(comment_done_handler); request.fail(comment_fail_handler); // fail promise callback }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="comment-fields"> <div class="commenter-comment"> <div class="form-group col-md-12"> <textarea data-comment-field-type="commenter_comment" class="form-control commenter-field" title="User's comment" placeholder="Comment Text">Some comment...</textarea> </div> </div> <div class="commenter-name-email"> <input type="hidden" data-comment-field-type="commenter_parent" class="commenter-field" value="some parrent"> <input type="hidden" data-comment-field-type="commenter_user_id" class="commenter-field" value="some UserId"> <input type="hidden" data-comment-field-type="per_page" class="commenter-field" value="some number of comments"> </div> <div class="commenter-captcha"> <div class="col-md-3 text-right"> <a href="javascript:void(0)" class="btn btn-info post-this-comment">Comment</a> </div> </div> </div> 

在开发工具中检查请求标头会显示正在发送的以下数据:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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