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

时间:2015-10-17 01:10:30

标签: javascript php jquery json ajax

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

到目前为止,我所得到的只是这个错误,好像我没有填写我所说的评论文字。

  

SQLSTATE [23000]:完整性约束违规:1048列“注释”不能为空(SQL:插入commentsuser_idcommentparent_id,{ {1}},parentsupdated_at)值(1,,0,2015-10-17 00:57:59,2015-10-17 00:57:59))

created_at给出了类似的内容。

console.log(formData)

我怎样才能做到这一点?如果有更好的方法请建议。

HTML

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

Javascript

 <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>

我正在使用PhpStrom,点击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 }); 指向此文件

  

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

这是FormData()

FormData

2 个答案:

答案 0 :(得分:1)

我建议使用regular objects因为它们更容易使用formData(在我看来)。

jQuery文档状态Type: PlainObject or String or Array表示ajax帖子中的数据设置,这让我觉得它们也像对象一样。

相反,您的点击处理程序可以:

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);

答案 1 :(得分:0)

更简单的方法是在元素上使用数据属性,只需从您的值构建数据字符串,如下所示:

$(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>

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

enter image description here