programing

$ (this) .serialize () — 값을 추가하는 방법?

nasanasas 2020. 8. 31. 07:56
반응형

$ (this) .serialize () — 값을 추가하는 방법?


현재 다음이 있습니다.

$.ajax({
    type: 'POST',
    url: this.action,
    data: $(this).serialize(),
});

이것은 잘 작동하지만 데이터에 값을 추가하고 싶으므로 시도했습니다.

$.ajax({
    type: 'POST',
    url: this.action,
    data: $(this).serialize() + '&=NonFormValue' + NonFormValue,
});

그러나 그것은 올바르게 게시되지 않았습니다. 직렬화 문자열에 항목을 추가하는 방법에 대한 아이디어가 있습니까? 이것은 특정 양식이 아닌 전역 페이지 변수입니다.


대신에

 data: $(this).serialize() + '&=NonFormValue' + NonFormValue,

당신은 아마 원합니다

 data: $(this).serialize() + '&NonFormValue=' + NonFormValue,

값에 NonFormValue특수 문자가 포함되어있는 경우 URL 인코딩에주의해야합니다 .


matt b의 답변이 작동하지만을 사용 .serializeArray()하여 양식 데이터에서 배열을 가져 와서 수정하고을 사용 jQuery.param()하여 URL 인코딩 양식으로 변환 할 수도 있습니다. 이런 식으로 jQuery는 추가 데이터의 직렬화를 처리합니다.

var data = $(this).serializeArray(); // convert form to array
data.push({name: "NonFormValue", value: NonFormValue});
$.ajax({
    type: 'POST',
    url: this.action,
    data: $.param(data),
});

먼저 항목을 추가 한 다음 직렬화합니다.

$.ajax({
    type: 'POST',
    url: this.action,
    data: $.extend($(this), {'NonFormValue': NonFormValue}).serialize()
});

첫째로해서는 안됩니다

data: $(this).serialize() + '&=NonFormValue' + NonFormValue,

있다

data: $(this).serialize() + '&NonFormValue=' + NonFormValue,

둘째로 당신은 사용할 수 있습니다

url: this.action + '?NonFormValue=' + NonFormValue,

또는 조치에 이미 매개 변수가 포함되어

url: this.action + '&NonFormValue=' + NonFormValue,

Don't forget you can always do:

<input type="hidden" name="NonFormName" value="NonFormValue" />

in your actual form, which may be better for your code depending on the case.


We can do like:

data = $form.serialize() + "&foo=bar";

For example:

var userData = localStorage.getItem("userFormSerializeData");
var userId = localStorage.getItem("userId");

$.ajax({
    type: "POST",
    url: postUrl,
    data: $(form).serialize() + "&" + userData + "&userId=" + userId,
    dataType: 'json',
    success: function (response) {
        //do something
    }
});

You can write an extra function to process form data and you should add your nonform data as the data valu in the form.seethe example :

<form method="POST" id="add-form">
    <div class="form-group required ">
        <label for="key">Enter key</label>
        <input type="text" name="key" id="key"  data-nonformdata="hai"/>
    </div>
    <div class="form-group required ">
        <label for="name">Ente Name</label>
        <input type="text" name="name" id="name"  data-nonformdata="hello"/>
    </div>
    <input type="submit" id="add-formdata-btn" value="submit">
</form>

Then add this jquery for form processing

<script>
$(document).onready(function(){
    $('#add-form').submit(function(event){
        event.preventDefault();
        var formData = $("form").serializeArray();
        formData = processFormData(formData);
        // write further code here---->
    });
});
processFormData(formData)
{
    var data = formData;
    data.forEach(function(object){
        $('#add-form input').each(function(){
            if(this.name == object.name){
                var nonformData = $(this).data("nonformdata");
                formData.push({name:this.name,value:nonformData});
            }
        });
    });
    return formData;
}

참고URL : https://stackoverflow.com/questions/6539502/this-serialize-how-to-add-a-value

반응형